Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Here is the original code which has defined String-Array (25). It is working perfectly. But I don't need to define it as 25. Instead, I used arraylist. Please check my code.

Using String of array:

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;  
        }

Here, I need to change String-Array to Arraylist. I tried something like this,

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;  
        }

Email ids are get from database instead of example.com.

But I am getting java.lang.ArrayIndexOutOfBoundsException: 0 error in this line. emailAddress[i]=(rs.getString("EmailAddress"));

Please help!

share|improve this question

5 Answers 5

This is not how you use an ArrayList.

First, you need to write:

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

So, program to the interface and use the Java 7 diamond operator.

Next, remove the index i. You don't need this.

Finally, just do:

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

To convert it back to an String[] you can then do:

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

Here is my suggestion for you final code:

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()]);
}

I have removed your pointless assignments to null. I have added try-with-resources blocks to close your external resources, you code was one massive memory leak.

share|improve this answer
    
i value is to iterate the result set to get the emailaddress from database. How can I remove it? Can you please answer it as full code –  user3152748 Jun 19 '14 at 8:27
    
@user3152748 You are mistaken. Your i value is only used to index into the array you have now removed. It is not necessary with a list. You have been provided with enough info in this answer to solve the problem - just apply a little brain power to it. –  Duncan Jun 19 '14 at 8:46
    
Will check the code.. –  user3152748 Jun 19 '14 at 9:22
    
Code is working as expected. But getting java.lang.ArrayIndexOutOfBoundsException: 2 and java.lang.NullPointerException error.. –  user3152748 Jun 19 '14 at 10:40
    
From where? You either update your question or post a new question with the stacktrace. –  Boris the Spider Jun 19 '14 at 10:42

If you have a ArrayList, then you dont need a array again, indeed a ArrayList is backed by Array itself and its dynamic in size.

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

And ArrayList#toArray converts List to Array which has done at last in the code.

share|improve this answer
    
Getting java.lang.ArrayIndexOutOfBoundsException: 2 error. :( –  user3152748 Jun 19 '14 at 8:30
    
When it returns, I need the value to be as string of array. Please consider! –  user3152748 Jun 19 '14 at 8:32
    
yes that is why emailAddress.toArray(new String[emailAddress.size()]), it converts your ArrayList to Array And remember no need of array into the method. –  Subhrajyoti Majumder Jun 19 '14 at 9:20
    
Will check the code bro.. –  user3152748 Jun 19 '14 at 9:29
    
Code is working as expected. But getting java.lang.ArrayIndexOutOfBoundsException: 2 and java.lang.NullPointerException error.. –  user3152748 Jun 19 '14 at 10:38

declare it as

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

convert it to String[]:

return emailAddress.toArray(new String[emailAddress.size()]);
share|improve this answer
    
AtLast I need to convert it to Array of String..I dont need the return value to be in ArrayList –  user3152748 Jun 19 '14 at 8:23
    
You know the size, use it. Calling new String[0]{} causes the creation of two arrays - the empty one you pass in and one of the correct size. This is a little wasteful. –  Boris the Spider Jun 19 '14 at 8:25
    
It's a so tiny consumption that can be ignroed. –  J.Rush Jun 19 '14 at 8:27

You use ArrayList here wrongly in your code. When you define

ArrayList<String> strArrEmailIds = new ArrayList<String>();
String[] emailAddress= new String[strArrEmailIds.size()];
strArrEmailIds.toArray(emailAddress);

strArrEmailIds by default has a size of 0, so the generated emailAddress array also gets a length of 0. Later in the while loop, you are trying to assign the value to the emailAddress[0], it will throw ArrayIndexOutOfBoundsException.

Instead, the correct way is :

ArrayList<String> strArrEmailIds = new ArrayList<String>();
//....
while(rs.next()){
    //....
    strArrEmailIds.add(rs.getString("EmailAddress"));
}
//....
String[] emailAddress = strArrEmailIds.toArray(new String[strArrEmailIds.size()]);
share|improve this answer
java.lang.ArrayIndexOutOfBoundsException: 0 if your result set goes beyond 25 itteration.

How to convert array to ArrayList ?

Arrays.asList(myArray)

in your case you can have a list and in the resulset itteration you can add them to the list like

List<String> emails = new ArrayList<String>();
while(...){
emails.add(rs.getString("EmailAddress"));
}
share|improve this answer
    
Arrays.asList is of fixed size. This doesn't change anything apart from access semantics. –  Boris the Spider Jun 19 '14 at 8:26
    
@BoristheSpider: Agree..OP has asked for how to convert so gave an option of asList...in the second paragraph has given the solution.... –  Jayaram Pradhan Jun 19 '14 at 8:29
    
you mean I should have pointed like : new ArrayList(Arrays.asList(myArray)) this you mean? –  Jayaram Pradhan Jun 19 '14 at 8:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.