Insert and Extract ArrayList Order

Suppose I insert 5 rows in an ArrayList . Will the insert and extract order from the ArrayList same?

+52
java collections
Jul 04 '12 at 15:04
source share
5 answers

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); } } } 

It produces the following output:

 Inserted in 'order': one two three four five Inserted out of 'order': four five one two three 

For more information, see the documentation: List (Java Platform SE7)

+41
Jul 04 2018-12-12T00:
source share

Yes ArrayList is a sequential list . Thus, the insertion and extraction order is the same.

If you add items during the search , the order will not remain the same.

+86
Jul 04 2018-12-12T00:
source share

If you always add to the end, each element will be added to the end and remain so until you change it.

If you always insert at the beginning, each item will be displayed in the order in which you added them.

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

+31
Jul 04 2018-12-12T00:
source share

Yes, it will always be the same. From document

Adds the specified item to the end of this list. Parameters: e element to be added to this list. Returns: true (as specified in Collection.add (java.lang.Object))

ArrayList add() implementation

 public boolean More ...add(E e) { ensureCapacity(size + 1); // Increments modCount!! elementData[size++] = e; return true; } 
+5
Mar 14 '17 at 16:27
source share

Yes, he remains the same. but why not check it out easily? Create an ArrayList, populate it, and then retrieve the elements!

0
Jul 04 2018-12-12T00:
source share



All Articles