0

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!

asked Jun 19, 2014 at 8:19
0

5 Answers 5

3

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.

answered Jun 19, 2014 at 8:23
Sign up to request clarification or add additional context in comments.

5 Comments

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 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.
Code is working as expected. But getting java.lang.ArrayIndexOutOfBoundsException: 2 and java.lang.NullPointerException error..
From where? You either update your question or post a new question with the stacktrace.
yours and Subhrajyoti Majumder code is working good..but geting the error :(
2

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.

answered Jun 19, 2014 at 8:25

5 Comments

Getting java.lang.ArrayIndexOutOfBoundsException: 2 error. :(
When it returns, I need the value to be as string of array. Please consider!
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.
Code is working as expected. But getting java.lang.ArrayIndexOutOfBoundsException: 2 and java.lang.NullPointerException error..
It must somewhere else, if it is then post a new question with detail dude
0

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()]);
answered Jun 19, 2014 at 8:22

3 Comments

AtLast I need to convert it to Array of String..I dont need the return value to be in ArrayList
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.
It's a so tiny consumption that can be ignroed.
0

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()]);
answered Jun 19, 2014 at 8:36

Comments

-1
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"));
}
answered Jun 19, 2014 at 8:23

3 Comments

Arrays.asList is of fixed size. This doesn't change anything apart from access semantics.
@BoristheSpider: Agree..OP has asked for how to convert so gave an option of asList...in the second paragraph has given the solution....
you mean I should have pointed like : new ArrayList(Arrays.asList(myArray)) this you mean?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.