List继承了Collection,是有序的列表.
主要实现类有ArrayList、LinkedList、Vector、Stack等
ArrayList :
LinkedList :
Node<E> node(int index) {
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
Vector :
Stack :
CopyOnWriteArrayList :
继承了Collection,值无序不可重复。 主要实现类有
HashSet、Hashtable、TreeSet、LinkedHashSet等
HashSet:
private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
TreeSet:
LinkedHashSet:
CopyOnWriteArraySet:
/**
* Appends the element, if not present.
*
* @param e element to be added to this list, if absent
* @return {@code true} if the element was added
*/
public boolean addIfAbsent(E e) {
Object[] snapshot = getArray();
return indexOf(e, snapshot, 0, snapshot.length) >= 0 ? false :
addIfAbsent(e, snapshot);
}
Map 是不同于Collection的一种键-值对(key-value)集合,
主要实现类有HashMap、LinkedHashMap、TreeMap、HashTable等。
HashMap:
// Hash表初始容量 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//数组最大容量 1073741824
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认加载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; //key hashCode取模运算后在数组中对应的index下标
final K key; //数据的key
V value; //数据的value
Node<K,V> next; //指向下一个节点
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//put方法懒加载实现
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
static final int TREEIFY_THRESHOLD = 8;//默认链表元素大于等于8可被树化
static final int MIN_TREEIFY_CAPACITY = 64; //可树化的最小表容量为 64,
//putVal method
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//哈希表容量<64,继续扩容而不树化
//防止哈希表容量较小,哈希碰撞的几率会比较大,导致出现长链表
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
//todo 这里转化红黑树
}
}
TreeMap :
static final class Entry<K,V> implements Map.Entry<K,V> {
K key;
V value;
Entry<K,V> left;
Entry<K,V> right;
Entry<K,V> parent;
boolean color = BLACK;
}
Hashtable: