HashMap原理/HashMap内部代码---HashMap说明书

来源:互联网 发布:百旺税控盘开票软件 编辑:程序博客网 时间:2024/06/01 23:07

HashMap的内部说明以及解释


package com.sun.HashMap;/** * 注意几点: * 1.每次扩容为原来的二倍 * 2.扩容的时候需要重新hash,因为元素在数组中的位置为hash*(table.length()-1) * 3.最大容量为2^30 * 4.容量必须是2的次幂 * 5.阈值threshold为LoadFactory*Capacity 即负载因子*容量 * @author:孙创 * @date:2017年2月17日 */import java.util.Map;//链表型数组public class MyHashMap<K, V> {public static void main(String[] args) {MyHashMap<Integer, String> h = new MyHashMap<Integer, String>(3);String put = h.put(1, "1sunchaung");System.out.println(put);String put2 = h.put(2, "2zhangle");System.out.println(put2);String put3 = h.put(3, "3fan");System.out.println(put3);String put4 = h.put(4, "4pwng");System.out.println(put4);String put5 = h.put(5, "5pwng");String put6 = h.put(6, "6pwng");int size2 = h.size;System.out.println(size2);String remove = h.remove(4);System.out.println(remove);}// 系统默认初始容量,必须是2的n次幂,这是处于优化考虑的final static int DEFAULT_INITIAL_CAPACITY = 16;// 设置系统默认最大容量final int MAXIMUM_CAPACITY = 1 << 30;// 系统默认负载因子,可在构造函数中指定final static float DEFAULT_LOAD_FACTOR = 0.75f;// 用于存储的表,长度可以调整,且必须是2的n次幂transient Entry<K, V>[] table;// 当前的Map的key——value映射数,也就是当前的sizetransient int size;// 阈(yu)值int threshold;// 哈希表的负载因子final float loadFactor;// map结构被改变的次数transient volatile int modCount;public MyHashMap(int initialCapacity, float loadFactor) {if (initialCapacity < 0)throw new IllegalArgumentException("Illegal initial capacity: "+ initialCapacity);if (initialCapacity > MAXIMUM_CAPACITY)initialCapacity = MAXIMUM_CAPACITY;if (loadFactor <= 0 || Float.isNaN(loadFactor))throw new IllegalArgumentException("Illegal load factor: "+ loadFactor);// 寻找一个2的k次幂capacity恰好大于initialcapacityint capacity = 1;while (capacity < initialCapacity) {capacity <<= 1;}// 设置加载因子this.loadFactor = loadFactor;// 设置阈值为capacity*loadFactor,实际当HashMap当前size达到这个阈值的时候,HashMap就需要扩大一倍threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);table = new Entry[capacity];init();}public MyHashMap(int initialCapacity) {this(initialCapacity, DEFAULT_LOAD_FACTOR);}public MyHashMap() {this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);}public V get(Object key) {if (key == null)return getForNullKey();Entry<K, V> entry = getEntry(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;}return null;}// 下面这两个方法是一套hash算法,用来计算数组值  第一个方法,得到哈希值,第二个方法,根据哈希值计算元素在数组中的位置。final int hash(Object k) {int h = k.hashCode();h ^= (h >>> 20) ^ (h >>> 12);return h ^ (h >>> 7) ^ (h >>> 4);}// "h&(length-1)"其实这里有点小巧妙,为什么是做与运算?// 首先我们要确定,HashMap的数组长度永远是偶数,所以length-1一定是一个奇数,// 假设现在的长度是16,length-1就是15,对应的二进制是:1111。// 假设有两个元素,一个哈希值是8,二进制是1000,一个哈希值是9,二进制是1001。和1111与运算后,// 分别还是1000和1001,他们被分配在了数组的不同位置,这样,哈希的分布非常均匀。// 那么如果数组的长度是奇数,减去1后就是偶数了,偶数对应的二进制最低位一定是0,例如14二进制1110。// 对上面两个数字分别与运算,得到1000和1000。这样,哈希值8和9的元素会被存储在数组同一个位置的链表中。// 在操作的时候,链表中的元素越多,效率就会越低,因为要不停的对链表循环比较。// 所以这个方法降低了哈希冲突的概率//计算出元素在数组中的下标static int indexFor(int h, int length) {return h & (length - 1);}// 在找到元素在数组中的索引位置以后,会循环遍历table[i]所在的链表,如果找到key值与传入的key值相同的对象,// 则替换并返回原对象;若找不到,则通过addEntry(hash,key,value,i)添加新的对象public V put(K key, V value) {if (key == null)return putForNullKey(value);int hash = hash(key);int i = indexFor(hash, table.length);//如果key值存在,则直接覆盖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))) {V oldValue = e.value;e.value = value;// 有就覆盖return oldValue;}}// 没有找到的话重新创建addEntry(hash, key, value, i);return null;}private V putForNullKey(V value) {for (Entry<K, V> e = table[0]; e != null; e = e.next) {if (e.key == null) {V oldValue = e.value;e.value = value;return oldValue;}}addEntry(0, null, value, 0);return null;}// 以上过程就是新建一个Entry对象,并放在当前位置的Entry链表的头部。然后判断size是否达到了需要扩容的界限并让size// 增加1,如果达到了扩容的界限则调用resize(int capacity)方法。void addEntry(int hash, K key, V value, int bucketIndex) {Entry<K, V> e = table[bucketIndex];// 该位置原来的链表table[bucketIndex] = new Entry<K, V>(hash, key, value, e);// 新元素的next为原来的链表值if (size++ >= threshold)// 如果容量>=(capacity * loadFactor)的话,扩容resize(2 * table.length);// 数组扩容,为原来容量的二倍}// 扩容并且将所有的元素重新哈希,因为容量增大,每个元素的hash值和位置都发生改变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];//将所有的元素重新hashtransfer(newTable);table = newTable;threshold = (int) Math.min(newCapacity * loadFactor,MAXIMUM_CAPACITY + 1);}// tranfer方法将所有的元素重新哈希,因为新的容量变大,所以每个元素的位置改变。void transfer(Entry[] newTable) {// 保留原数组的引用到src中,Entry[] src = table;// 新容量使新数组的长度int newCapacity = newTable.length;// 遍历原数组for (int j = 0; j < src.length; j++) {// 获取元素eEntry<K, V> e = src[j];if (e != null) {// 将原数组中的元素置为nullsrc[j] = null;// 遍历原数组中j位置指向的链表do {Entry<K, V> next = e.next;// 根据新的容量计算e在新数组中的位置int i = indexFor(e.hash, newCapacity);// 将e插入到newTable[i]指向的链表的头部e.next = newTable[i];newTable[i] = e;e = next;} while (e != null);}}}private void init() {}final Entry<K, V> getEntry(Object key) {int hash = (key == null) ? 0 : hash(key);for (Entry<K, V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {Object k;if (e.hash == hash&& ((k = e.key) == key || (key != null && key.equals(k))))return e;}return null;}public V remove(Object key) {Entry<K, V> e = removeEntryForKey(key);return (e == null ? null : e.value);}final Entry<K, V> removeEntryForKey(Object key) {int hash = (key == null) ? 0 : hash(key);int i = indexFor(hash, table.length);Entry<K, V> prev = table[i];Entry<K, V> e = prev;while (e != null) {Entry<K, V> next = e.next;Object k;// 如果找到if (e.hash == hash&& ((k = e.key) == key || (key != null && key.equals(k)))) {size--;if (prev == e)table[i] = next;elseprev.next = next;// 节点前一个的下一个等于节点的下一个return e;}// 如果没找到prev = e;e = next;}return e;}private static class Entry<K, V> implements Map.Entry<K, V> {final K key;V value;Entry<K, V> next;int hash;Entry(int h, K k, V v, Entry<K, V> n) {value = v;key = k;next = n;hash = h;}@Overridepublic K getKey() {return key;}@Overridepublic V getValue() {return value;}@Overridepublic V setValue(V newvalue) {V oldvalue = value;value = newvalue;return oldvalue;}public final boolean equals(Object o) {if (!(o instanceof Map.Entry))return false;Map.Entry e = (Map.Entry) o;Object k1 = getKey();Object k2 = e.getKey();if (k1 == k2 || (k1 != null && k1.equals(k2))) {Object v1 = getValue();Object v2 = e.getValue();if (v1 == v2 || (v1 != null && v1.equals(v2)))return true;}return false;}public final int hashCode() {return (key == null ? 0 : key.hashCode())^ (value == null ? 0 : value.hashCode());}public final String toString() {return getKey() + "=" + getValue();}}}


1 0
原创粉丝点击