ArrayList insertion and retrieval order
Solution 1:
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.
Solution 2:
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)
Solution 3:
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.
Solution 4:
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;
}