Reputation: 3329
I have a String array like,
String[] abc= new String[]{};
and my List has some values. I iterate the list and add each list element to string array.
for(int i=0; i<errList.size(); i++)
{
abc[i] = errList.get(i).getSrceCd();
}
errList.size() has 6 values. But when the for loops executed I get java.lang.ArrayIndexOutOfBoundsException. Any inputs?
Upvotes: 0
Views: 122
Reputation: 5883
I would just do this
String[] abc= errList.toArray(new String[errList.size()]);
Upvotes: 0
Reputation: 54074
String[] abc = errList.toArray(new String[0]);
Or:
String[] abc = new String[errList.size()];
errList.toArray(abc);
Upvotes: 0
Reputation: 49
Did you try to use for each loop which is widely used in collection framework?
Upvotes: 0
Reputation: 67502
You're creating a String[]
object of zero length; so, when you try to assign an item to abc[i]
, it is accessing an index not within your bounds 0 <= i < 0
.
You should allocate abc
with a length instead:
String[] abc= new String[errList.size()];
for(int i=0; i<errList.size(); i++)
{
abc[i] = errList.get(i).getSrceCd();
}
Upvotes: 5
Reputation: 18584
You need to craete the string array with the same size as the list. It is not dynamic. Perhaps you can tell what you are trying to achieve with this exercise.
Upvotes: 0