2

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

    }

4 Answers 4

11

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

Sign up to request clarification or add additional context in comments.

Comments

3

You never use

it.next();

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

1 Comment

Thanks a lot, that was my next mistake, which I haven't thought of. It is working now :)
0

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

2 Comments

Even better: Collections.copy( l2, l1 );
List<String> l1 = Arrays.asList(args); List<String> l2 = new ArrayList<String>(l1);
0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.