数组列表插入和检索顺序

假设我在 ArrayList中插入5个字符串。从 ArrayList插入和提取的顺序是否相同?

197661 次浏览

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 it remains the same. but why not easily test it? Make an ArrayList, fill it and then retrieve the elements!

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)

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