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


You are using the wrong method to add items.

Or:

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

      

or preferably:



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

      

set tries to replace an element that currently exists, but nothing else.

Additional Information

+11


source


You never use

it.next();

      



Maybe that's not the point, but I don't think you need an infinite loop.

+3


source


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


Once you have a stack trace, use USE to figure out where the failure occurred! Here put () is a dead sale to re-post in the javadoc.

0


source







All Articles