Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do all Lists in Java maintain insertion order

The List javadocs mentions that Lists are ordered. However, I cannot see anything specifying the nature of the ordering. Can we rely on lists e.g. ArrayList and LinkedList maintaining insertion order?

I am asking about the instance where we do not call set or sort.

like image 243
Andy Cribbens Avatar asked Mar 06 '18 17:03

Andy Cribbens


1 Answers

However, I cannot see anything specifying the nature of the ordering.

Funnily enough, it's mentioned in the second sentence of its documentation:

The user of this interface has precise control over where in the list each element is inserted.

Without calling List#set or List#sort, the only methods that will add elements to the List are List#add and List#addAll, both of which append them to the end (unless you call one of the overloaded methods and specify an index); you can also add elements to the List via its ListIterator.

If List did not maintain insertion order, it would have mentioned it in its documentation. If you're still unsure, feel free to look over the source code, which is available online.

like image 181
Jacob G. Avatar answered Sep 30 '22 20:09

Jacob G.