hashmap实现原理浅析
HashMap和Hashtable的区别
- 两者最主要的区别在于Hashtable是线程安全,而HashMap则非线程安全
Hashtable 的实现方法里面都添加了synchronized关键字来确保线程同步,因此相对而言HashMap性能会高一些,我们平时使用时若无特殊需求建议使用 HashMap,在多线程环境下若使用HashMap需要使用Collections.synchronizedMap()方法来获取一个线程安全的集合 (Collections.synchronizedMap()实现原理是 Collections定义了一个SynchronizedMap的内部类,这个类实现了Map接口,在调用方法时使用synchronized来保证线 程同步,当然了实际上操作的还是我们传入的HashMap实例,简单的说就是Collections.synchronizedMap()方法帮我们在操 作HashMap时自动添加了synchronized来实现线程同步,类似的其它Collections.synchronizedXX方法也是类似原 理) - HashMap可以使用null作为key,而Hashtable则不允许null作为key
虽说HashMap支持null值作为key,不过建议还是尽量避免这样使用,因为一旦不小心使用了,若因此引发一些问题,排查起来很是费事
HashMap以null作为key时,总是存储在table数组的第一个节点上 - HashMap是对Map接口的实现,HashTable实现了Map接口和Dictionary抽象类
- HashMap的初始容量为16,Hashtable初始容量为11,两者的填充因子默认都是0.75
HashMap扩容时是当前容量翻倍即:capacity*2,Hashtable扩容时是容量翻倍+1即:capacity*2+1 - 两者计算hash的方法不同
Hashtable计算hash是直接使用key的hashcode对table数组的长度直接进行取模1 int hash = key.hashCode(); 2 int index = (hash & 0x7FFFFFFF) % tab.length;
HashMap计算hash对key的hashcode进行了二次hash,以获得更好的散列值,然后对table数组长度取摸
1 static int hash(int h) { 2 // This function ensures that hashCodes that differ only by 3 // constant multiples at each bit position have a bounded 4 // number of collisions (approximately 8 at default load factor). 5 h ^= (h >>> 20) ^ (h >>> 12); 6 return h ^ (h >>> 7) ^ (h >>> 4); 7 } 8 9 static int indexFor(int h, int length) { 10 return h & (length-1); 11 }
-
HashMap和Hashtable的底层实现都是数组+链表结构实现
HashSet和HashMap、Hashtable的区别
除开HashMap和Hashtable外,还有一个hash集合HashSet,有所区别的是HashSet不是key value结构,仅仅是存储不重复的元素,相当于简化版的HashMap,只是包含HashMap中的key而已
通过查看源码也证实了这一点,HashSet内部就是使用HashMap实现,只不过HashSet里面的HashMap所有的value都是同一 个Object而已,因此HashSet也是非线程安全的,至于HashSet和Hashtable的区别,HashSet就是个简化的HashMap 的,所以你懂的
下面是HashSet几个主要方法的实现
1 private transient HashMap<E,Object> map; 2 private static final Object PRESENT = new Object(); 3 4 public HashSet() { 5 map = new HashMap<E,Object>(); 6 } 7 public boolean contains(Object o) { 8 return map.containsKey(o); 9 } 10 public boolean add(E e) { 11 return map.put(e, PRESENT)==null; 12 } 13 public boolean add(E e) { 14 return map.put(e, PRESENT)==null; 15 } 16 public boolean remove(Object o) { 17 return map.remove(o)==PRESENT; 18 } 19 20 21 public void clear() { 22 map.clear(); 23 }
HashMap和Hashtable的实现原理
HashMap和Hashtable的底层实现都是数组+链表结构实现的,这点上完全一致
添加、删除、获取元素时都是先计算hash,根据hash和table.length计算index也就是table数组的下标,然后进行相应操作,下面以HashMap为例说明下它的简单实现
1 /** 2 * HashMap的默认初始容量 必须为2的n次幂 3 */ 4 static final int DEFAULT_INITIAL_CAPACITY = 16; 5 6 /** 7 * HashMap的最大容量,可以认为是int的最大值 8 */ 9 static final int MAXIMUM_CAPACITY = 1 << 30; 10 11 /** 12 * 默认的加载因子 13 */ 14 static final float DEFAULT_LOAD_FACTOR = 0.75f; 15 16 /** 17 * HashMap用来存储数据的数组 18 */ 19 transient Entry[] table; 20 21 复制代码
- HashMap的创建
HashMap默认初始化时会创建一个默认容量为16的Entry数组,默认加载因子为0.75,同时设置临界值为16*0.75
1 /** 2 * Constructs an empty <tt>HashMap</tt> with the default initial capacity 3 * (16) and the default load factor (0.75). 4 */ 5 public HashMap() { 6 this.loadFactor = DEFAULT_LOAD_FACTOR; 7 threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR); 8 table = new Entry[DEFAULT_INITIAL_CAPACITY]; 9 init(); 10 }
- put方法
HashMap会对null值key进行特殊处理,总是放到table[0]位置
put过程是先计算hash然后通过hash 与table.length取摸计算index值,然后将key放到table[index]位置,当table[index]已存在其它元素时,会在 table[index]位置形成一个链表,将新添加的元素放在table[index],原来的元素通过Entry的next进行链接,这样以链表形式 解决hash冲突问题,当元素数量达到临界值(capactiy*factor)时,则进行扩容,是table数组长度变为table.length*2
1 public V put(K key, V value) { 2 if (key == null) 3 return putForNullKey(value); //处理null值 4 int hash = hash(key.hashCode());//计算hash 5 int i = indexFor(hash, table.length);//计算在数组中的存储位置 6 //遍历table[i]位置的链表,查找相同的key,若找到则使用新的value替换掉原来的oldValue并返回oldValue 7 for (Entry<K,V> e = table[i]; e != null; e = e.next) { 8 Object k; 9 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { 10 V oldValue = e.value; 11 e.value = value; 12 e.recordAccess(this); 13 return oldValue; 14 } 15 } 16 //若没有在table[i]位置找到相同的key,则添加key到table[i]位置,新的元素总是在table[i]位置的第一个元素,原来的元素后移 17 modCount++; 18 addEntry(hash, key, value, i); 19 return null; 20 } 21 22 23 void addEntry(int hash, K key, V value, int bucketIndex) { 24 //添加key到table[bucketIndex]位置,新的元素总是在table[bucketIndex]的第一个元素,原来的元素后移 25 Entry<K,V> e = table[bucketIndex]; 26 table[bucketIndex] = new Entry<K,V>(hash, key, value, e); 27 //判断元素个数是否达到了临界值,若已达到临界值则扩容,table长度翻倍 28 if (size++ >= threshold) 29 resize(2 * table.length); 30 }
- get方法
同样当key为null时会进行特殊处理,在table[0]的链表上查找key为null的元素
get的过程是先计算hash然后通过hash与table.length取摸计算index值,然后遍历table[index]上的链表,直到找到key,然后返回 -
1 public V get(Object key) { 2 if (key == null) 3 return getForNullKey();//处理null值 4 int hash = hash(key.hashCode());//计算hash 5 //在table[index]遍历查找key,若找到则返回value,找不到返回null 6 for (Entry<K,V> e = table[indexFor(hash, table.length)]; 7 e != null; 8 e = e.next) { 9 Object k; 10 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) 11 return e.value; 12 } 13 return null; 14 }
- remove方法
remove方法和put get类似,计算hash,计算index,然后遍历查找,将找到的元素从table[index]链表移除 -
1 public V remove(Object key) { 2 Entry<K,V> e = removeEntryForKey(key); 3 return (e == null ? null : e.value); 4 } 5 final Entry<K,V> removeEntryForKey(Object key) { 6 int hash = (key == null) ? 0 : hash(key.hashCode()); 7 int i = indexFor(hash, table.length); 8 Entry<K,V> prev = table[i]; 9 Entry<K,V> e = prev; 10 11 while (e != null) { 12 Entry<K,V> next = e.next; 13 Object k; 14 if (e.hash == hash && 15 ((k = e.key) == key || (key != null && key.equals(k)))) { 16 modCount++; 17 size--; 18 if (prev == e) 19 table[i] = next; 20 else 21 prev.next = next; 22 e.recordRemoval(this); 23 return e; 24 } 25 prev = e; 26 e = next; 27 } 28 29 return e; 30 }
- resize方法
resize方法在hashmap中并没有公开,这个方法实现了非常重要的hashmap扩容,具体过程为:先创建一个容量为 table.length*2的新table,修改临界值,然后把table里面元素计算hash值并使用hash与table.length*2重新计 算index放入到新的table里面
这里需要注意下是用每个元素的hash全部重新计算index,而不是简单的把原table对应index位置元素简单的移动到新table对应位置 -
1 void resize(int newCapacity) { 2 Entry[] oldTable = table; 3 int oldCapacity = oldTable.length; 4 if (oldCapacity == MAXIMUM_CAPACITY) { 5 threshold = Integer.MAX_VALUE; 6 return; 7 } 8 9 Entry[] newTable = new Entry[newCapacity]; 10 transfer(newTable); 11 table = newTable; 12 threshold = (int)(newCapacity * loadFactor); 13 } 14 15 void transfer(Entry[] newTable) { 16 Entry[] src = table; 17 int newCapacity = newTable.length; 18 for (int j = 0; j < src.length; j++) { 19 Entry<K,V> e = src[j]; 20 if (e != null) { 21 src[j] = null; 22 do { 23 Entry<K,V> next = e.next; 24 //重新对每个元素计算index 25 int i = indexFor(e.hash, newCapacity); 26 e.next = newTable[i]; 27 newTable[i] = e; 28 e = next; 29 } while (e != null); 30 } 31 } 32 }
- clear()方法
clear方法非常简单,就是遍历table然后把每个位置置为null,同时修改元素个数为0
需要注意的是clear方法只会清楚里面的元素,并不会重置capactiy -
1 public void clear() { 2 modCount++; 3 Entry[] tab = table; 4 for (int i = 0; i < tab.length; i++) 5 tab[i] = null; 6 size = 0; 7 }
- containsKey和containsValue
containsKey方法是先计算hash然后使用hash和table.length取摸得到index值,遍历table[index]元素查找是否包含key相同的值 -
1 public boolean containsKey(Object key) { 2 return getEntry(key) != null; 3 } 4 final Entry<K,V> getEntry(Object key) { 5 int hash = (key == null) ? 0 : hash(key.hashCode()); 6 for (Entry<K,V> e = table[indexFor(hash, table.length)]; 7 e != null; 8 e = e.next) { 9 Object k; 10 if (e.hash == hash && 11 ((k = e.key) == key || (key != null && key.equals(k)))) 12 return e; 13 } 14 return null; 15 }
- containsValue方法就比较粗暴了,就是直接遍历所有元素直到找到value,由此可见HashMap的containsValue方法本质上和普通数组和list的contains方法没什么区别,你别指望它会像containsKey那么高效
-
1 public boolean containsValue(Object value) { 2 if (value == null) 3 return containsNullValue(); 4 5 Entry[] tab = table; 6 for (int i = 0; i < tab.length ; i++) 7 for (Entry e = tab[i] ; e != null ; e = e.next) 8 if (value.equals(e.value)) 9 return true; 10 return false; 11 }
- hash和indexFor
indexFor中的h & (length-1)就相当于h%length,用于计算index也就是在table数组中的下标
hash方法是对hashcode进行二次散列,以获得更好的散列值
为了更好理解这里我们可以把这两个方法简化为 int index= key.hashCode()/table.length,以put中的方法为例可以这样替换 -
1 int hash = hash(key.hashCode());//计算hash 2 int i = indexFor(hash, table.length);//计算在数组中的存储位置 3 //上面这两行可以这样简化 4 int i = key.key.hashCode()%table.length;
1 static int hash(int h) { 2 // This function ensures that hashCodes that differ only by 3 // constant multiples at each bit position have a bounded 4 // number of collisions (approximately 8 at default load factor). 5 h ^= (h >>> 20) ^ (h >>> 12); 6 return h ^ (h >>> 7) ^ (h >>> 4); 7 } 8 9 10 static int indexFor(int h, int length) { 11 return h & (length-1); 12 }
原文地址:http://www.cnblogs.com/lzrabbit/p/3721067.html#h1

浙公网安备 33010602011771号