HashMap继承至Abstract抽象类,是基于哈希表的Map接口的非同步实现,此实现提供所有可选的映射操作,并允许使用null 值和 null 键。(除了非同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同。)此类不保证映射的顺序,特别是它不保证该顺序恒久不变 (摘至Api1.6中文文档)。下面就说说对HashMap的理解。
public V put(K key, V value) { if (key == null)//null键处理 return putForNullKey(value); int hash = hash(key.hashCode());//重新计算hash值 int i = indexFor(hash, table.length);//找到数组中的索引 for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k;//若索引处Entry不为null,则循环比较,找到相同的key替换旧值就返回 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } //没找到或者此处entry==null modCount++;//记录hashmap中修改结构的次数 addEntry(hash, key, value, i);//添加数据 return null; }
/** * The table, resized as necessary. Length MUST Always be a power of two. */ transient Entry[] table;
static int hash(int h) { // This function ensures that hashCodes that differ only by // constant multiples at each bit position have a bounded // number of collisions (approximately 8 at default load factor). h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); }可以看出此方法就是一个数学运算。 接下来程序会调用 indexFor(int h, int length) 方法来计算该对象应该保存在 table 数组的哪个索引处
/** * Returns index for hash code h. */ static int indexFor(int h, int length) { return h & (length-1); }这个方法非常巧妙,它总是通过 h
&
(table.length -1) 来得到该对象的保存位置;我们就来分析一下它为什么巧妙、高效。
// Find a power of 2 >= initialCapacity int capacity = 1; while (capacity < initialCapacity) capacity <<= 1;
这就保证了table数组的长度始终是2的n次方。(无参构造函数,默认初始化数组长度是16)。当length总是 2 的n次方时,h& (length-1)运算等价于h%length,但&比%效率高。
继续put方法,接下来程序就会根据indexFor方法返回的索引找到对应数组中的元素及其链表,并与put的key进行循环比较,若已存在相同的key,则替换value即可;若未匹配到,则程序进入addEntry方法:
void addEntry(int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex];//先存放此索引在table中的元素的引用 //在new一个新的Entry对象,并指向上一步得到的对象的引用,这样就形成了链表结构 table[bucketIndex] = new Entry<K,V>(hash, key, value, e); if (size++ >= threshold)//当存放元素size到达极限时, resize(2 * table.length);//扩容() }
比较简单,就是将新Entry对象存放在table[bucketIndex]处,并指向之前存放在此处的Entry对象,这样就形成了链表结构。
到这里,我想大家应该大致清楚HashMap的内部存储结构了,就是数组+链表结构,新加入的对象总是存放在数组中,通过引用指向老对象。画张图理解下:
从上图中可以看出,HashMap底层就是一个数组结构,数组中的每一项都可以形成一个链表。
public V get(Object key) { // 如果 key 是 null,调用 getForNullKey 取出对应的 value if (key == null) return getForNullKey(); // 根据该 key 的 hashCode 值计算它的 hash 码 int hash = hash(key.hashCode()); // 直接取出 table 数组中指定索引处的值, for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; // 搜索该 Entry 链的下一个 Entry e = e.next) { Object k; // 如果该 Entry 的 key 与被搜索 key 相同 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) return e.value; } return null; }
void resize(int newCapacity) { Entry[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity == MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return; } Entry[] newTable = new Entry[newCapacity];//新建一个数组 transfer(newTable); table = newTable; threshold = (int)(newCapacity * loadFactor); } /** * Transfers all entries from current table to newTable. */ void transfer(Entry[] newTable) { Entry[] src = table; int newCapacity = newTable.length; for (int j = 0; j < src.length; j++) { Entry<K,V> e = src[j];//索引处的Entry对象e if (e != null) { src[j] = null;//将原数组此处引用设置为null do { Entry<K,V> next = e.next;//拿到e的下一个对象引用 int i = indexFor(e.hash, newCapacity);//在新的数组容量中计算此hash值的索引位置 e.next = newTable[i];//将e下一个对象指向当前对象引用(恰好和原数据链表结构顺序相反参考addEntry方法) newTable[i] = e;//将当前对象e存放到新数组newTable[i]中 e = next; } while (e != null); } } }
2.负载因子loadFactor,默认是0.75。
增大负载因子可以减少 Hash 表(就是那个 Entry 数组)所占用的内存空间,但会增加查询数据的时间开销(因为同一位置形成的链表数据增多),而查询是最频繁的的操作(HashMap 的 get() 与 put() 方法都要用到查询);减小负载因子会提高数据查询的性能,但会增加 Hash 表所占用的内存空间。
我们可以在创建 HashMap 时根据实际需要适当地调整 load factor 的值;如果程序比较关心空间开销、内存比较紧张,可以适当地增加负载因子;如果程序比较关心时间开销,内存比较宽裕则可以适当的减少负载因子。通常情况下,程序员无需改变负载因子的值,默认值0.75,,是时间和空间成本上一种折衷。
3.初始容量initialCapacity
在前面我们分析过HashMap扩容的过程,它会新创建一个数组(length为原来的2倍),然后循环从老数组中copy所有数据,个人认为还是比较耗时的,所以根据实际需要设置一个合理的初始容量还是很有必要的。
4.hashcode方法的实现 --- 参考Java理论与实践(哈希)
这个方法写得好,会使数据均匀分布,进而提高Hashmap的效率。