ArrayMap
优势:
- 相比 hashMap 不会重建 hash映射,不会创建额外的对象。 2. 删除时 缩小存储当前数组 (重点) 1. remove() 2. removeAt()
// 满足 大于 (BASE_SIZE * 2) 且 长度 小于 mHashes 三分之一
if (mHashes.length > (BASE_SIZE * 2) && mSize < mHashes.length / 3) {
// Shrunk enough to reduce size of arrays. We don't allow it to
// shrink smaller than (BASE_SIZE*2) to avoid flapping between
// that and BASE_SIZE.
final int n = osize > (BASE_SIZE * 2) ? (osize + (osize >> 1)) : (BASE_SIZE * 2);
final int[] ohashes = mHashes;
final Object[] oarray = mArray;
allocArrays(n);
- size == 4 || size == 8 内存分配有可能进入 缓存池。
- 二分法精妙之处 数据可以更快定位 配合数组 直接定位到。
- 扩容规律 ( 都在默认情况下: 比 hashMap 扩容要小 内存占用小) 4 8 ( 8 > (osize + (osize >> 1) ) )
- System.arraycopy 使用
//当需要插入的位置不在数组末尾时,需要将index位置后的数据通过拷贝往后移动一位
if (index < osize) {
System.arraycopy(mHashes, index, mHashes, index + 1, osize - index);
System.arraycopy(mArray, index << 1, mArray, (index + 1) << 1, (mSize - index) << 1);
}
说明:
key的hash 值 会存入 hash数组中,
array 对象 存储方式时 key(index =0 ) value (index = 1)
节省资源,节省内存
劣势:
1. 不合适大量数据,效率比hashmap 低。
2. 不可以线程并发操作
小技巧: 明确数据容量: 设置 capacity = 4 || capacity = 8 而不是设置 3 || 7