[java] ArrayList insertion and retrieval order

Suppose I insert 5 strings in an ArrayList. Will the order of insertion and retrieval from the ArrayList be the same?

This question is related to java collections

The answer is


If you always add to the end, then each element will be added to the end and stay that way until you change it.

If you always insert at the start, then each element will appear in the reverse order you added them.

If you insert them in the middle, the order will be something else.


Yes. ArrayList is a sequential list. So, insertion and retrieval order is the same.

If you add elements during retrieval, the order will not remain the same.


Yes, it will always be the same. From the documentation

Appends the specified element to the end of this list. Parameters: e element to be appended to this list Returns: true (as specified by Collection.add(java.lang.Object))

ArrayList add() implementation

public boolean More ...add(E e) {
    ensureCapacity(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

Yes it remains the same. but why not easily test it? Make an ArrayList, fill it and then retrieve the elements!