如何将 ArrayList 转换为 Array [重复]

Posted

技术标签:

【中文标题】如何将 ArrayList 转换为 Array [重复]【英文标题】:How to convert an ArrayList to Array [duplicate] 【发布时间】:2019-05-17 18:06:24 【问题描述】:

我无法将整个数组列表传递给我的 java 程序中的方法。 我在论坛中搜索并尝试了一些其他程序员能够解决的解决方案,但在我的程序中我无法实现。

我已在此处附上代码,并突出显示了我面临问题的那一行。

import java.io.File;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;

import com.mercury.itg.ws.dm.client.AddRequestNotesDocument;
import com.mercury.itg.ws.dm.client.AddRequestNotesResponseDocument;
import com.mercury.itg.ws.dm.client.Column;
import com.mercury.itg.ws.dm.client.CreateRequestDocument;
import com.mercury.itg.ws.dm.client.CreateRequestResponseDocument;
import com.mercury.itg.ws.dm.client.DeleteRequestsDocument;
import com.mercury.itg.ws.dm.client.DeleteRequestsResponseDocument;
import com.mercury.itg.ws.dm.client.DemandServiceStub;
import com.mercury.itg.ws.dm.client.ExecuteWFTransitionsDocument;
import com.mercury.itg.ws.dm.client.ExecuteWFTransitionsResponseDocument;
import com.mercury.itg.ws.dm.client.GetRequestsDocument;
import com.mercury.itg.ws.dm.client.GetRequestsResponseDocument;
import com.mercury.itg.ws.dm.client.Identifier;
import com.mercury.itg.ws.dm.client.Note;
import com.mercury.itg.ws.dm.client.RemoteReference;
import com.mercury.itg.ws.dm.client.Request;
import com.mercury.itg.ws.dm.client.SetRequestFieldsDocument;
import com.mercury.itg.ws.dm.client.SetRequestFieldsResponseDocument;
import com.mercury.itg.ws.dm.client.SetRequestRemoteReferenceStatusDocument;
import com.mercury.itg.ws.dm.client.SetRequestRemoteReferenceStatusResponseDocument;
import com.mercury.itg.ws.dm.client.SimpleField;
import com.mercury.itg.ws.dm.client.Table;
import com.mercury.itg.ws.dm.client.URLReference;

import oracle.jdbc.OracleTypes;
import oracle.jdbc.OracleDriver;

public class PMCDeleteRequest 

    protected ConfigurationContext ctx = null;

    public PMCDeleteRequest() 
        final String repositoryPath = System.getProperty("client.repository.dir");
        final String axis2 = repositoryPath + "/conf/client-axis2.xml";
        final File file = new File(axis2);
        if (file.exists()) 
            try 
                this.ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(repositoryPath, axis2);
             catch (final Exception e) 
                e.printStackTrace();
                System.exit(1);
            
        
    
      String name;
     public void setName(String name) 
            this.name = name;
        
    /**
     * The main program Parameter: args[0] - service URL. e.g.
     * http://server:port/itg/ppmservices/DemandService
     */

    public static void main(final String[] args) throws Exception 

        String URL = args[0];
        String username = args[1];
        String password = args[2];
        String requestids = args[3];
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection con = DriverManager.getConnection(URL, username, password);
        String request_ids = requestids;
        String commaSeparateRequestIds = request_ids.replaceAll("#@#", ",");
        String request_delete_sql = "SELECT REQUEST_ID FROM (SELECT KFMP.REQUEST_ID FROM KCRT_FG_MASTER_PROJ_REF KFMP, PM_PROJECTS PP WHERE KFMP.REF_MASTER_PROJECT_ID = PP.PROJECT_ID AND PP.PROJECT_ID IN ("
                + commaSeparateRequestIds + "))";
        PreparedStatement sgStmt = con.prepareStatement(request_delete_sql);
        ResultSet rs = sgStmt.executeQuery();
        List<String> delete = new ArrayList<String>();
        try 
        while (rs.next()) 

            final String serviceURL = "https://.../DemandService";
            String requestId = Integer.toString(rs.getInt(1));

            delete.add(requestId);


        
        System.out.println("arraylist: "+delete);


                pmc.deleteRequests(serviceURL,delete);  // Here i am unable to pass the entire arraylist

             

        catch (final Exception e) 
                if (e instanceof org.apache.axis2.AxisFault) 
                    final org.apache.axis2.AxisFault xe = (org.apache.axis2.AxisFault) e;
                    System.out.println(xe.getMessage());
                    System.out.println("---detail---");
                    final Iterator iter = xe.getDetail().getChildElements();
                    while (iter.hasNext()) 
                        final OMElement item = (OMElement) iter.next();
                        System.out.println(item.getText());
                    
                    System.out.println("------------");
                 else 
                    throw e;

                
                System.exit(1);
            

        rs.close();
        con.close();

    

    private void deleteRequests(final String serviceURL, final String[] requestIds) throws Exception 

        // construct the Identifier array
        final Identifier[] ids = new Identifier[requestIds.length];

        for (int i = 0; i < requestIds.length; i++) 

            ids[i] = Identifier.Factory.newInstance();
            ids[i].setId(requestIds[i]);

        

        // get Webservice handle

        final DemandServiceStub stub = new DemandServiceStub(this.ctx, serviceURL);

        // Construct message to send
        final DeleteRequestsDocument inDoc = DeleteRequestsDocument.Factory.newInstance();

        final DeleteRequestsDocument.DeleteRequests deletes = inDoc.addNewDeleteRequests();

        deletes.setRequestIdsArray(ids);

        //Set the path for cacerts for searching certificate before invoking web service
System.setProperty("javax.net.ssl.trustStore","C:\\Java\\jdk1.7.0_80\\jre\\lib\\security\\cacerts");
// Invoke web service
        final DeleteRequestsResponseDocument outDoc = stub.deleteRequests(inDoc);

        // Process the return request
        final int returnCode = outDoc.getDeleteRequestsResponse().getReturn();
        System.out.println("Delete Requests Succeeded. Return Code: " + returnCode);
    


我在将整个数组列表传递给方法时遇到的问题:

pmc.deleteRequests(serviceURL,delete);

这里的 deleteRequests 参数可以有(String,String[])

任何指导/建议都会很有帮助。

感谢和问候, 萨米特

【问题讨论】:

确切的错误是什么? 我也不明白确切的问题是什么...... 您应该仔细检查您的公司是否扩展了对 Java 7 的支持。否则您应该升级。 你不应该给出整个代码。试着给出一段代码并解释清楚。读这么多代码很难。 在您的方法签名中,一个参数是array,类型为(String,String[]),但您传递的是ArrayList。这就是问题所在,除非你这样做; delete.toArray() 【参考方案1】:

使用toArray(T[] a) 方法将List 转换为数组。

String[] deleteArray = delete.toArray(new String[delete.size()]);
pmc.deleteRequests(serviceURL, deleteArray);

【讨论】:

toArray 方法只需要一个预期类型的​​数组。它的大小无关紧要。所以最好写: String[] deleteArray = delete.toArray(new String[0]); @Conffusion 在这里,大小确实很重要:如果您传递的数组太小,则会创建另一个数组。那是浪费性能。由于集合的大小是已知的,因此您应该使用正确的长度来实例化数组。 不知道这一点。测试并确认。今天学到了新东西。谢谢

以上是关于如何将 ArrayList 转换为 Array [重复]的主要内容,如果未能解决你的问题,请参考以下文章

我需要将 Array 转换为 ArrayList 帮助,不知道该怎么做? [复制]

将 ArrayList 转换为 Array 抛出 java.lang.ArrayStoreException

将 JSONarray 转换为 ArrayList

如何将字符串转换为数组,怎么办?

在 JSP 中从 Object ArrayList 转换为 Object Array

[转]Java中怎样把数组转换为ArrayList