您的位置:首页 > 理论基础 > 数据结构算法

java HashMap 原理 数据结构

2016-10-27 15:04 316 查看
//这是 map的容器
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

//这是 Entry对象 ,可以看出 Entry是链表
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
int hash;
}

首先存对象
put(key,value);

里面有一个这个方法
这个方法 需要两个参数 ,hash值和length ,这个length实际上就是 table.length
根据 hash值和length计算出一个index,两个不同的hash值计算出得到相同的index,就会记录在 链表里面
/**
* Returns index for hash code h.
*/
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
return h & (length-1);
}

当table.length长度不够,size是实际上table中非空元素的个数
size>threshold 临界值的时候就会自动扩容,扩容会两倍扩容,这是固定写死的
扩容后会重新建立table,table里面的元素index会 根据 table.length 和hash值 重新计算
threshold = table.length*loadFactor   这个比例默认是0.75
默认hashMap的容量是  16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}

createEntry(hash, key, value, bucketIndex);
}

hashMap的优点就是 插入和查询速度都很快
结合了 数组和链表的  存储方式
可更改的参数  初始容量默认16 和 阀值比例 默认0.75
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: