Java同步集合 源码笔记

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;
关注点
  1. modCount
  2. 扩容
    int newCapacity = oldCapacity + (oldCapacity >> 1)
  3. 迭代器
    保存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. 条件1:链表,长度>=8-1
  2. 条件2:容量,大于等于64.否则进行resize()
去树化
  1. 条件:链表,长度<=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;
说明

主要就是红黑树的实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值