> A collection is a container object that holds a group of objects, often referred to as elements. The Java Collections Framework supports three types of collections, named lists, sets, and maps.
> The ArrayList class and the LinkedList class are concrete implementations of the List interface. Which of the two classes you use depends on your specific needs. If you need to support random access through an index without inserting or removing elements from any place other than the end, ArrayList offers the most efficient collection. If, however, your application requires the insertion or deletion of elements from any place in the list, you should choose LinkedList. A list can grow or shrink dynamically. An array is fixed once it is created. If your application does not require insertion or deletion of elements, the most efficient data structure is the array.
List<Integer> arrayList = new ArrayList<Integer>(); // List是一个接口哦,
arrayList.add(1); // 1 is autoboxed to new Integer(1)
arrayList.add(2);
arrayList.add(3);
arrayList.add(1);
arrayList.add(4);
arrayList.add(0, 10);
arrayList.add(3, 30);
System.out.println("A list of integers in the array list:");
System.out.println(arrayList);
LinkedList<Object> linkedList = new LinkedList(arrayList);
linkedList.add(1, "red");
linkedList.removeLast();
linkedList.addFirst("green");
System.out.println("Display the linked list backward:");
for (int i = linkedList.size() - 1; i >= 0; i--) {
System.out.print(linkedList.get(i) + " ");
}
}
}
```
这个例子可以看到,这两个类型的使用几乎完全一样。
这里注意:`List<Integer> arrayList = new ArrayList<Integer>();`真实的对象是ArrayList,引用变量的类型是`List`;看看本章节的开始部分,List是一个接口,ArryList实现了List这个接口,因此可以使用接口来操作ArrayList对象。
```java
AbstractList<Integer> arrayList = new ArrayList<Integer>();
ArrayList<Integer> arrayList = new ArrayList<Integer>();
```
上面这样的赋值也是没有问题的,因为后面的代码只使用了List接口的功能(能力)。但是如果这样:
```java
Collection<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(1); // 1 is autoboxed to new Integer(1)