Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with the ArrayList class in Java

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

    }
like image 244
user42155 Avatar asked Jul 09 '26 12:07

user42155


1 Answers

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

like image 155
tster Avatar answered Jul 12 '26 02:07

tster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!