假设我在中插入5个字符串ArrayList
。插入和从中检索的顺序ArrayList
是否相同?
Answers:
检查下面的代码并运行:
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);
}
}
}
产生以下输出:
Inserted in 'order':
one
two
three
four
five
Inserted out of 'order':
four
five
one
two
three
有关详细信息,请参阅文档: List (Java Platform SE7)
是的,它保持不变。但是为什么不轻易测试呢?创建一个ArrayList,填充它,然后检索元素!