0

This is what printed out in the console while I tried to run the code below, I can not tell why the code is not compiling, and I do not see any issues. Please help!! Thanks.

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 2 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266) at java.base/java.util.Objects.checkIndex(Objects.java:359) at java.base/java.util.ArrayList.set(ArrayList.java:441) at Example.main(Example.java:9)

import java.util.*;

public class Example {

    public static void main(String[] args) {
        List<String> bucketList = new ArrayList<>();
        bucketList.add("Visit Alaska");
        bucketList.add("Visit Hawaii");
        bucketList.set(2, "Visit Japan");

        for (String list : bucketList) {
            System.out.print(list);
        }

        Set<String> codingJournal = new LinkedHashSet<>();
        codingJournal.add("2/10/2021");
        codingJournal.add("5/8/2021");
        codingJournal.add("7/31/2021");

        for (String journal : codingJournal) {
            System.out.print(journal);
        }

        Map<String, ArrayList<String>> BU = new HashMap<>();
        ArrayList<String> languages = new ArrayList<>();
        languages.add("Java");
        languages.add("SQL");
        ArrayList<String> classes = new ArrayList<>();
        classes.add("CS520");
        classes.add("CS669");
        BU.put("Languages", languages);
        BU.put("Classes", classes);

        System.out.println(BU.get("Classes"));

    }
}
cHappiness
  • 41
  • 6
  • 4
    The problem is on `bucketList.set(2, "Visit Japan");`. Check this for an answer: [IndexOutOfBoundsException when adding to ArrayList at index](https://stackoverflow.com/questions/23288439/indexoutofboundsexception-when-adding-to-arraylist-at-index) – Skod Jul 31 '21 at 19:48
  • 1
    Your code has compiled, this is an exception at runtime. – tgdavies Jul 31 '21 at 21:57

1 Answers1

2

You can have a look what the exception actually says:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 2 out of bounds
...
...
java.base/java.util.ArrayList.set(ArrayList.java:441) at Example.main(Example.java:9)

If you look at line number 9 in your Example.java class, you'll see, you're setting "Visit Japan" in the index no 2 of bucketList:

bucketList.set(2, "Visit Japan");

Where bucketList was just introduced and only 2 elements were added before that call:

List<String> bucketList = new ArrayList<>();
bucketList.add("Visit Alaska");
bucketList.add("Visit Hawaii");

Why is that?

If you look at the implementation of the ArrayList, you'll understand why. When you initialized an ArrayList, this is what is called:

public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

where the DEFAULTCAPACITY_EMPTY_ELEMENTDATA is:

private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = new Object[0];

If an add(Object obj) is called, then the following implementation is found in ArrayList class:

public boolean add(E e) {
    ++this.modCount;
    this.add(e, this.elementData, this.size);
    return true;
}

where this.add(...) says:

private void add(E e, Object[] elementData, int s) {
    if (s == elementData.length) {
        elementData = this.grow();
    }

    elementData[s] = e;
    this.size = s + 1;
}

So I think you can guess what is happening here. Your list was an array of default of size 0 when it was initialized and modified afterwards, in fact, with the add of new elements, the array size grow(). Let's see what this grow() does:

private Object[] grow() {
    return this.grow(this.size + 1);
}

private Object[] grow(int minCapacity) {
    return this.elementData = Arrays.copyOf(this.elementData, this.newCapacity(minCapacity));
}

So, you see, it creates an new Array with the capacity of new size.

So, when you've added first two elements, you've created an array of length 2 for your use. That is why whenever you're trying to set bucketList.set(2, "Visit Japan");, you're trying to access the index no 2 of an zero indexed array of length 2, which is obviously not in bound. Hence the ArrayIndexOutOfBoundException is thrown.

devReddit
  • 2,696
  • 1
  • 5
  • 20