Collection
java集合都继承了Collection接口,实现常用的方法
List
有序、可重复的列表,常用有ArrayList、LinkedList
ArrayList
底层数组,查询快O(1),增删慢,因为需要移动数据,且线程不安全的;源码的结构是 Object[] elementData
实现细节源码:(最好初始化设置容量,避免不断扩容)
public boolean add(E e) { 新增时会扩容,实例化时会产生初始大小 ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); } private void grow(int minCapacity) {//扩容,调用底层复制原数组 // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); //扩容1.5倍 if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); }
LinkedList
底层链表,查询慢,因为需要遍历数组,增删快,只需要修改指针就可,且线程不安全的;源码结构为Node对象
void linkLast(E e) { //新增时,移动首尾指针即可 final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; }
Set
无序、不可重复的列表,常用有HashSet、TreeSet
HashSet
底层采用HashMap,具体分析见HashMap,所以由此可见,HashMap在Java中真的算是经典
public HashSet() { map = new HashMap<>(); }
TreeSet
底层采用TreeMap,具体分析见TreeMap
public TreeSet() { this(new TreeMap<E,Object>()); }