Java同步集合 源码笔记
文章目录
1. List
ArrayList
属性
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] EMPTY_ELEMENTDATA = {};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
private static final int DEFAULT_CAPACITY = 10;
transient Object[] elementData;
private int size;
关注点
- modCount
- 扩容
int newCapacity = oldCapacity + (oldCapacity >> 1) - 迭代器
保存expectedModCount
next会检查modCount值是否符合预期,抛出并发修改异常
说明
1. transient Object[] elementData
自定义序列化:elementData的容量 >= 存储元素个数
效率更高,序列化后数据更少
2. modCount
对数组造成修改的,modCount++
修改:结构、数据。
结构,数组长度
数据,添加 删除
注意:set和get不影响modCount
3. 扩容
oldCapacity + (oldCapacity >> 1)
LinkedList
大部分机制同ArrayList
属性
transient int size = 0;
transient Node<E> first;
transient Node<E> last;
transient
自定义序列化:容量,数据
2. Set
基于HashMap等实现,值为下面的PRESENT对象
private transient HashMap<E,Object> map;
private static final Object PRESENT = new Object();
3. Map
HashMap
属性
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
static final float DEFAULT_LOAD_FACTOR = 0.75f;
static final int TREEIFY_THRESHOLD = 8; // 链表长度大于等于7,且容量大于等于64,链转红黑树
static final int MIN_TREEIFY_CAPACITY = 64;
static final int UNTREEIFY_THRESHOLD = 6; // 小于等于6,树转链表
// Node:k,v,next,hash
transient Node<K,V>[] table;
// keySet缓存
transient Set<Map.Entry<K,V>> entrySet;
// size为元素格式,threshold为HashMap容量
transient int size;
int threshold;
关注
// 1. 哈希计算式:hash
h = 0,或(h = key.hashCode()) ^ (h >>> 16)
// 2. 容量分配:tableSizeFor
this.threshold = tableSizeFor(initialCapacity);
// 3. 扩容:resize
// 4. 树化:treeifyBin
// 5. 去树化:
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
说明
容量分配
容量为2^n,原因:位操作效率高
扩容
newCap = oldCap << 1
树化
- 条件1:链表,长度>=8-1
- 条件2:容量,大于等于64.否则进行resize()
去树化
- 条件:链表,长度<=6
LinkedHashMap
属性
static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
transient LinkedHashMap.Entry<K,V> head;
transient LinkedHashMap.Entry<K,V> tail;
// 有序类型,true为访问顺序,false为插入顺序
final boolean accessOrder;
TreeMap(略)
属性
private final Comparator<? super K> comparator;
private transient Entry<K,V> root;
说明
主要就是红黑树的实现。