ArrayList insertion and retrieval order
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.
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 an ordered collection and it maintains the insertion order.
Check the code below and run it:
public class ListExample {
public static void main(String[] args) {
List<String> myList = new ArrayList<String>();
myList.add("one");
myList.add("two");
myList.add("three");
myList.add("four");
myList.add("five");
System.out.println("Inserted in 'order': ");
printList(myList);
System.out.println("\n");
System.out.println("Inserted out of 'order': ");
// Clear the list
myList.clear();
myList.add("four");
myList.add("five");
myList.add("one");
myList.add("two");
myList.add("three");
printList(myList);
}
private static void printList(List<String> myList) {
for (String string : myList) {
System.out.println(string);
}
}
}
Produces the following output:
Inserted in 'order':
one
two
three
four
five
Inserted out of 'order':
four
five
one
two
three
For detailed information, please refer to documentation: List (Java Platform SE7)