1. Collection(Interface)
(1) List(Interface):有序列表(插入顺序),可以插入多个null。
-
ArrayList
1. 底层实现为数组,方便根据索引查找元素,不适合在指定位置插入或删除元素,可以动态增加数组的大小。
2. 包含的常用方法:
1. add(E e);//在末尾添加指定类型的元素
2. add(int index,E e);//在指定索引位置添加元素
3. addAll(int index,Collection<E> c);//在指定索引位置添加集合c中的所有元素
3. remove(Object o);//删除指定元素
4. remove(int index);//删除指定索引位置的元素
5. get(int index);//获取指定索引位置的元素
6. <T> T[] toArray(T[] a); // String[] str=arr.toArray(String[] {});转化为指定类型的数组
3. 可以插入为空源码解析:底层为数组 Object[] elementData,可以插入任意类型的元素。
/**
* This helper method split out from add(E) to keep method
* bytecode size under 35 (the -XX:MaxInlineSize default value),
* which helps when add(E) is called in a C1-compiled loop.
*/
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length)
elementData = grow();
elementData[s] = e;
size = s + 1;
}
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
modCount++;
add(e, elementData, size);
return true;
}
-
LinkedList
1. 底层实现为双向链表,方便插入和删除元素,不适合获取指定位置的元素。
2. 实现了队列Queue接口,具有poll,peek,pop等方法。
3. 源码解析:
//链表的长度
transient int size = 0;
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
//链表的头
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
//链表的尾
transient Node<E> last;
//链表维护的Node的结构
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
-
Vector
1. 底层实现为数组结构,是线程安全的,但执行效率比ArrayList慢。ArrayList初始容量为0的数组,添加一个元素容量变为10,每次扩容为当前1.5倍,Vector初始容量为10的数组,扩容为当前2倍。
(成倍扩容的好处:成倍增加vector的push_back时间复杂度为O(1)的,增加固定个数push_back时间复杂度为O(n)的。以1.5倍扩容的好处:以1.5倍扩容,最后所需空间大小小于之前释放的连续空间的大小,可以做到空间复用;而以2倍扩容,所需空间大小始终大于之前释放空间总和,无法利用之前释放的空间)。
2. 源码分析:在修改,添加或获取某些位置的元素时,public方法由synchronized修饰,保证线程安全。
public synchronized void addElement(E obj) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = obj;
}
(2)Set(Interface):集合,不包含重复元素
-
HashSet
1. 底层实现为HashMap,包含无序不重复元素,可以包含一个null值。
2. 底层HashMap的key值用来存储set中的元素,value存储固定的常量。
-
TreeSet
1. 是sortedSet的唯一实现类,包含不重复有序元素,默认自然序。
2. 底层实现采用TreeMap实现,采用红黑树结构进行元素的存储。
3. 默认情况下采用对象的自然序进行排列,也可类实现Comparable接口,重写compareTo方法指定排序顺序,或者在创建TreeSet是传入比较器。