1 year ago

#75798

test-img

Stepan Borisov

Question about java.util.ArrayList realization

I understand that size and capacity are different things. My question is why can I insert at a random location in a newly created array, but cannot do so in a newly created ArrayList. And I understand how it works, I'm interested in the motivation for doing it this way in the source code.

I faced the problem that I can't add value to ArrayList after initialisation with index.

final ArrayList<Integer> a = new ArrayList<>(16);
a.add(9, 1);

This code will throw IndexOutOfBoundsException, this happens because of this method in ArrayList source code.

public void add(int index, E element) {
  rangeCheckForAdd(index);
  ...
}

    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

My question is why this restriction exists? As far as I know, when I init ArrayList inside of it allocated simple java array of Object with default capacity = 10 or another capacity, which I can provide to constructor.

Can anyone explain me what benefits we can get from that? Thanks a lot.

java

list

arraylist

collections

0 Answers

Your Answer

Accepted video resources