Problem with ArrayList class in Java
I have a problem with the following code. I am getting the error
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:571)
at java.util.ArrayList.set(ArrayList.java:364)
at Test.main(Test.java:17)
and I don't understand why. I have a list that is initialized, then I iterate over it and then I want to populate another list with the values of the first list. I don't understand why I am getting IndexOutOfBoundsException. It seems that my initialization is wrong. Thanks a lot in advance.
public static void main(String[] args) {
String s1 = "one";
String s2 = "one";
ArrayList list = new ArrayList();
list.set(0, s1);
list.set(1, s2);
Iterator it = list.iterator();
ArrayList listToFill = new ArrayList();
int k = 0;
while (it.hasNext()) {
String m = "m";
listToFill.set(k, m);
k++;
}
}
+2
source to share
4 answers
Why would you write this to copy one List to another?
This is much more eloquent:
import java.util.ArrayList;
import java.util.List;
public class ListDemo
{
public static void main(String[] args)
{
List<String> l1 = new ArrayList<String>(args.length);
for (String arg : args)
{
l1.add(arg);
}
System.out.println("l1: " + l1);
List<String> l2 = new ArrayList<String>(l1);
System.out.println("l2: " + l2);
}
}
0
source to share