HashMap源码解读

来源:互联网 发布:python 1分钟执行一次 编辑:程序博客网 时间:2024/06/04 19:40

一、构造函数:

    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);        // Find a power of 2 >= initialCapacity        int capacity = 1;        while (capacity < initialCapacity)            capacity <<= 1;        this.loadFactor = loadFactor;        threshold = (int)(capacity * loadFactor);        table = new Entry[capacity];        init();    }

第一个构造器:需要两个参数,第一个是HashMap的初始化大小的值,第二个是负载因子。对于initialCapacity,即初始化大小,其处理的办法是:

int capacity = 1;        while (capacity < initialCapacity)            capacity <<= 1;

也就是说,HashMap的初始容量是大于等于指定容量的第一个2^n的数,例如,指定为3的话,初始化容量是4,指定容量为5的话,初始化的大小就是8.


public HashMap(int initialCapacity) {        this(initialCapacity, DEFAULT_LOAD_FACTOR);    }
这个构造函数调用了第一个构造函数,负载因子使用默认值DEFAULT_LOAD_FACTOR(0.75f)。
 public HashMap() {        this.loadFactor = DEFAULT_LOAD_FACTOR;        threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);        table = new Entry[DEFAULT_INITIAL_CAPACITY];        init();    }
该构造函数是使用默认值构建HashMap,初始化大小为DEFAULT_INITIAL_CAPACITY(16),默认负载因子DEFAULT_LOAD_FACTOR(0.75f)。
 public HashMap(Map<? extends K, ? extends V> m) {        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);        putAllForCreate(m);    }

通过以上的构造器可以看出,HashMap的本质是内部有一个Entry的内部类,而HashMap则是一个Entry的数组类型,其结构如下:

 static class Entry<K,V> implements Map.Entry<K,V> {        final K key;        V value;        Entry<K,V> next;        final int hash;        /**         * Creates new entry.         */        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 (key==null   ? 0 : key.hashCode()) ^                   (value==null ? 0 : value.hashCode());        }        public final String toString() {            return getKey() + "=" + getValue();        }        /**         * This method is invoked whenever the value in an entry is         * overwritten by an invocation of put(k,v) for a key k that's already         * in the HashMap.         */        void recordAccess(HashMap<K,V> m) {        }        /**         * This method is invoked whenever the entry is         * removed from the table.         */        void recordRemoval(HashMap<K,V> m) {        }    }
该类比较简单,属性包括key、value、hash和next,next是一个Entry类型的引用,用于解决hash冲突,使用链表的形势将冲突的Entry链接在后面。

二、hashmap的基本操作:

1、put方法:

public V put(K key, V value) {        if (key == null)            return putForNullKey(value);        int hash = hash(key.hashCode());        int i = indexFor(hash, table.length);        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;    }
如果key为空的时候,执行putForNullKey方法:

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;                e.recordAccess(this);                return oldValue;            }        }        modCount++;        addEntry(0, null, value, 0);        return null;    }
先查找在Entry数组的第一个元素上及链表上查找是否存在key为null的value,如果存在,更新value值,如果不存在,则调用addEntry(0, null, value, 0);方法。而put方法对于key为非空的处理是,先通过hash方法算出一个hash值,然后通过indexFor方法计算出存储的位置,该方法的两个参数分别是hash值和Entry数组(table)的长度:

static int indexFor(int h, int length) {        return h & (length-1);    }
然后的处理也是先在table[i]的位置查看是否存在key为entry的对象,如果存在,则更新value,如果不存在,执行addEntry(hash, key, value, i);
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);        if (size++ >= threshold)            resize(2 * table.length);    }
该方法是在table的第i个位置上加入到Entry的链表上,这里面有一个非常重要的方法是resize,该方法可以动态扩充HashMap的大小:

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);    }
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];            if (e != null) {                src[j] = null;                do {                    Entry<K,V> next = e.next;                    int i = indexFor(e.hash, newCapacity);                    e.next = newTable[i];                    newTable[i] = e;                    e = next;                } while (e != null);            }        }    }
先通过resize方法创建一个原来两倍大小的新的Entry数组,然后通过transfer方法进行重新hash,将原来数组的元素拷贝到新的数组中。

2、get方法,put方法弄明白了,get方法就比较简单了:

  public V get(Object key) {        if (key == null)            return getForNullKey();        int hash = hash(key.hashCode());        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.equals(k)))                return e.value;        }        return null;    }
查找的过程就是通过key先找到Entry数组中的位置,然后在链表上去查找对应value。

JAVA中的HashMap基本原理就这样,其他的方法都跟以上的类似,大家可以自己去查看。





0 0