views:

526

answers:

4

Hi,

I have a problem with the following code. I obtain the error message

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, which is initialised, then I iterate over it, and then I want to fill another list with the values of the first list. I don't understand why I get IndexOutOfBoundsException. It seems that my initialisation is not correct. 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++;
     }

    }
+11  A: 

You are using the wrong method to add items.

Either:

list.add(0, s1);
list.add(1, s2);

or preferably:

list.add(s1);
list.add(s2);

set tries to replace the item that is currently there, but nothing is there yet.

More info

tster
+3  A: 

You never use

it.next();

Maybe this is not the point, but I don't think you want an infinite loop.

Alberto Zaccagni
nice catch, I missed that.
tster
Thanks a lot, that was my next mistake, which I haven't thought of. It is working now :)
A: 

Why on earth would you write this to copy one List into another?

This is far more succinct:

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);
   }
}
duffymo
Even better:Collections.copy( l2, l1 );
Stefan Kendall
or l2.addAll(l1);
tster
`List<String> l1 = Arrays.asList(args); List<String> l2 = new ArrayList<String>(l1);`
Tom Hawtin - tackline
A: 

When you have a stack trace thn USE it to figure out where the crash happened! Here the put() is a dead giveaway to reinvastigate in the javadoc.

Thorbjørn Ravn Andersen