jdk7 HashSet和HashMap源码分析

时间:2025-02-13 21:05:38

先来看看HashMap的一些成员变量以及他们的含义

 /**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;//默认Entry数组的长度 /**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;//加载因子,和数组长度有关 /**
* The table, resized as necessary. Length MUST Always be a power of two.
*/
transient Entry<K,V>[] table;//HashMap底层实现就是Entry数组,以后说的数组就是这个数组 /**
* The number of key-value mappings contained in this map.
*/
transient int size; //添加元素的个数

HashSet的底层实现就是用HashMap实现的。

hashset的add方法就是用hashmap的put方法。key是添加的元素,value是hashset维护的一个常量。这里不多说了,主要还是分析HashMap的源代码。

    public V put(K key, V value) {
if (key == null)
return putForNullKey(value);//添加键为null的元素
int hash = hash(key);//得到key的hash值,这个hash值是对key的hashcode进行过处理的
int i = indexFor(hash, table.length);//根据hash值和数组长度得到元素保存到数组中的位置
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
//判断将要添加元素的位置是否有元素了
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
//根据hashcode和equals方法判断键是否重复了,如果键重复了,将值替换了,并返回原来的值。
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
//如果键不重复,则添加到数组中
modCount++;
addEntry(hash, key, value, i);//hash值,键,值,插入到数组的位置(索引)
return null;
}
    /**
* Offloaded version of put for null keys
*/
private V putForNullKey(V value) {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null) {//添加的key为null,如果已经存在key为null的元素,则替换原来的值,返回旧值
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);//添加第一个key为null的元素
return null;
} //可以看出,添加key为null的元素每次都是添加到数组的第一个位置,重复添加key为null的元素,新值替换旧值
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);//如果元素个数大于threshold(这个数是一个数乘以加载因子,与加载因子相乘的这个数与初始化数组长度有关) 扩容为原来的两倍
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);//得到一个新的位置
} createEntry(hash, key, value, bucketIndex);
}
   void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];//得到存在数组中该位置的元素
table[bucketIndex] = new Entry<>(hash, key, value, e);//将新添加的元素存到该位置上,并关联之前保存在该位置上的数组
size++;//元素个数+1
}
    static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
int hash; /**
* Creates new entry.
*/
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
...
}
//Entry的结构

总结:当添加key为null的元素,会保存在数组的第一个位置上。其他key不为null的情况,是根据key的hash值来判断保存都Entry数组中的位置,如果该位置上没有元素,则直接添加。如果数组中已经在该位置上有元素了,根据hashcode和equals方法来判断键是否重复,如果重复,则替换旧值,并返回旧值。如果不重复,则将新元素添加到数组的索引上,然后通过Entry的next属性关联之前保存在该位置上的元素。当元素的个数大于某个值(不作详解)且该位置上有元素时,数组长度扩容为原来的两倍。

上面是添加元素,下面是取元素。

    public V get(Object key) {
if (key == null)
return getForNullKey();//获取键为null的值
Entry<K,V> entry = getEntry(key);//根据key获取元素 return null == entry ? null : entry.getValue();
}
    private V getForNullKey() {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;//返回key为null的值
}
return null;//如果不存在key为null,则返回null
}
    final Entry<K,V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key);//得到key的hash值
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {//根据key的hash值来索引保存在数组中的位置,如果索引到的位置有元素,判断key是否一致,直到判断完该位置上的所有元素,如果都不匹配,则返回null。如果该位置上没有元素,则返回null。
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;//不存在key则返回null
}