HashMap基于hashing原理,我们通过put()和get()方法储存和获取对象。当我们将键值对传递给put()方法时,它调用键对象的hashCode()方法来计算hashcode,让后找到位置来储存值对象。当获取对象时,通过键对象的equals()方法找到正确的键值对,然后返回值对象。HashMap使用链表来解决碰撞问题,当发生碰撞了,对象将会储存在链表的下一个节点中。 HashMap在每个链表节点中储存键值对对象。
成员变量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 //初始化大小 static final int MAXIMUM_CAPACITY = 1 << 30; //最大值 static final float DEFAULT_LOAD_FACTOR = 0.75f //加载因子 transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE; //存储数据 transient int size; // 大小 int threshold; //map大小临界点 final float loadFactor; //加载因子 transient int modCount; //修改次数 |
static class Entry<K,V> implements Map.Entry<K,V> { final K key; //key V value; //值 Entry<K,V> next; //下一个节点 int hash; //hash值 Entry(int h, K k, V v, Entry<K,V> n) { value = v; next = n; key = k; hash = h; } public final K getKey() { return key; } public final V getValue() { return value; } public final 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 Objects.hashCode(getKey()) ^ Objects.hashCode(getValue()); } public final String toString() { return getKey() + "=" + getValue(); } void recordAccess(HashMap<K,V> m) { } void recordRemoval(HashMap<K,V> m) { } } |
//主要进行一些值的初始化 public HashMap(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); this.loadFactor = loadFactor; threshold = initialCapacity; init(); } |
public HashMap(Map<? extends K, ? extends V> m) { //调用上面进行一些 初始化 this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR); //新建数组 inflateTable(threshold); //想table中添加值 putAllForCreate(m); } |
put方法
public V put(K key, V value) { //数组为空进行初始化 if (table == EMPTY_TABLE) { inflateTable(threshold); } //key为空 把数据放在table[0]的位置上 if (key == null) return putForNullKey(value); //根据key计算hash值 int hash = hash(key); //根据hash值和数组长度找到key对应entry在table中的位置 int i = indexFor(hash, table.length); //循环对应的entry 判断key是否重复 如果重复替换value 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; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null; } void addEntry(int hash, K key, V value, int bucketIndex) { //判断是否需要扩容 if ((size >= threshold) && (null != table[bucketIndex])) { //扩容长度为一倍 resize(2 * table.length); //重新计算hash值 hash = (null != key) ? hash(key) : 0; //重新计算存储位置 bucketIndex = indexFor(hash, table.length); } createEntry(hash, key, value, bucketIndex); } //创建一个entry 插入table中 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++; } //扩容方法 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, initHashSeedAsNeeded(newCapacity)); //用新数组替换旧数组 table = newTable; //计算下一个临界点 threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1); } |
get方法
public V get(Object key) { if (key == null) //key==null 取出table【0】的值 return getForNullKey(); Entry<K,V> entry = getEntry(key); return null == entry ? null : entry.getValue(); } final Entry<K,V> getEntry(Object key) { if (size == 0) { return null; } //计算hash值 然后根据hash值找到对应entry 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) { if (size == 0) { return null; } //计算hash值 找到对应的entry 取出值 进行链表的指向 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)))) { modCount++; size--; if (prev == e) table[i] = next; else prev.next = next; e.recordRemoval(this); return e; } prev = e; e = next; } return e; } |
总结
HashMap使线程不安全的效率高
HashMap可以存储 null值 null键
HashMap进行扩容的时候,需要进行新旧数组的复制操作 ,尽量避免HashMap进行扩容影响性能