如何在java中将String Array更改为ArrayList

时间:2014-06-19 08:19:15

标签: java arrays string arraylist

这是定义了String-Array(25)的原始代码。它工作得很好。但我不需要将它定义为25.相反,我使用了arraylist。请检查我的代码。

使用数组的字符串:

public String[] getemailAddr(String strAccountnbr) throws Exception {


        String strQuery2 = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
        String[] emailAddress = new String[25];

        int i=0;

         strQuery2 =  "SELECT c.EmailAddress AS EmailAddress" +

            " FROM customeremailid c " +
            "WHERE c.AccountNbr = ? " ;

          logMsg("strQuery2: "+strQuery2);

          ps = getDBConn().prepareStatement(strQuery2);
          ps.setString(1, strAccountnbr);        
          rs = ps.executeQuery();

        while(rs.next())
        {

                emailAddress[i]=(rs.getString("EmailAddress")); 
                logMsg("emailAddress[i]"+" "+i+": "+emailAddress[i]);   
                i=i+1;

            }

        return emailAddress;  
        }

在这里,我需要将String-Array更改为Arraylist。我试过这样的事,

public String[] getemailAddr(String strAccountnbr) throws Exception {


        String strQuery2 = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
       //Newly tried // 
        ArrayList<String> strArrEmailIds = new ArrayList<String>();
        String[] emailAddress= new String[strArrEmailIds.size()];
        strArrEmailIds.toArray(emailAddress);
        //Newly tried // 
        int i=0;

         strQuery2 =  "SELECT c.EmailAddress AS EmailAddress" +

            " FROM customeremailid c " +
            "WHERE c.AccountNbr = ? " ;

          logMsg("strQuery2: "+strQuery2);

          ps = getDBConn().prepareStatement(strQuery2);
          ps.setString(1, strAccountnbr);        
          rs = ps.executeQuery();

        while(rs.next())
        {

                emailAddress[i]=(rs.getString("EmailAddress")); 
                logMsg("emailAddress[i]"+" "+i+": "+emailAddress[i]);   
                i=i+1;

            }

        return emailAddress;  
        }

电子邮件ID是从数据库而不是example.com获取的。

但我得到了  java.lang.ArrayIndexOutOfBoundsException: 0错误  在这一行。 emailAddress[i]=(rs.getString("EmailAddress"));

请帮忙!

5 个答案:

答案 0 :(得分:3)

这不是您使用ArrayList的方式。

首先,你需要写:

List<String> strArrEmailIds = new ArrayList<>();

因此,编程到interface并使用Java 7钻石操作符。

接下来,删除索引i。你不需要这个。

最后,只需:

emailAddress.add(rs.getString("EmailAddress")); 

要将其转换回String[],您可以执行以下操作:

String[] arr = emailAddress.toArray(new String[emailAddress.size()]);

以下是我对你最终代码的建议:

public String[] getemailAddr(String strAccountnbr) throws Exception {
    final List<String> emailAddress = new ArrayList<>();
    final String strQuery2 = "SELECT c.EmailAddress AS EmailAddress"
            + " FROM customeremailid c "
            + "WHERE c.AccountNbr = ? ";
    try (final PreparedStatement ps = getDBConn().prepareStatement(strQuery2)) {
        ps.setString(1, strAccountnbr);
        try (final ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                emailAddress.add(rs.getString("EmailAddress"));
            }
        }
    }
    return emailAddress.toArray(new String[emailAddress.size()]);
}

我已将您无意义的作业移至null。我已经为关闭您的外部资源添加了try-with-resources块,您的代码是一个巨大的内存泄漏。

答案 1 :(得分:2)

如果您有ArrayList,那么您不需要再次使用数组,ArrayList本身支持Array及其动态大小。

List<String> emailAddress= new ArrayList<String>(); // dynamic array
...
while(rs.next()){
    emailAddress.add((rs.getString("EmailAddress"));
    ...
}
return emailAddress.toArray(new String[emailAddress.size()]); // creating array of String type

ArrayList#toArrayList转换为代码中最后完成的Array

答案 2 :(得分:0)

将其声明为

ArrayList<String> emailAddress= new ArrayList<String>();
...
emailAddress.add((rs.getString("EmailAddress")); 

将其转换为String []:

return emailAddress.toArray(new String[emailAddress.size()]);

答案 3 :(得分:0)

您在代码中错误地使用ArrayList。定义时

ArrayList<String> strArrEmailIds = new ArrayList<String>();
String[] emailAddress= new String[strArrEmailIds.size()];
strArrEmailIds.toArray(emailAddress);
默认情况下,

strArrEmailIds的大小为0,因此生成的emailAddress数组的长度也为0.稍后在while循环中,您尝试将值赋给{{1 },它会抛出emailAddress[0]

相反,正确的方法是:

ArrayIndexOutOfBoundsException

答案 4 :(得分:-1)

java.lang.ArrayIndexOutOfBoundsException: 0 if your result set goes beyond 25 itteration.

如何将array转换为ArrayList

Arrays.asList(myArray)

在您的情况下,您可以拥有list,并且在resulset帐户中,您可以将其添加到列表中,例如

List<String> emails = new ArrayList<String>();
while(...){
emails.add(rs.getString("EmailAddress"));
}