android HashMap源码分析

来源:互联网 发布:启动gta5需要网络连接 编辑:程序博客网 时间:2024/05/18 02:47

HashMap 数据结构

数据结构中有数组与链表两种模式,但是这两种模式都存在一定的缺陷

数组

数组:数组的存储区域是连续的,占用内存比较严重,空间复杂度比较高,但是数组在查找时是比较简单的。数组特点:查找容易,删除、插入比较复杂

链表

链表:链表的存储区域是不连续的,占用内存比较宽松,但是当在链表中查找某一个元素时是比较复杂的。链表特点:删除、插入比较简单,查找比较复杂。

HashMap是一种数据存储的容器,并且很好的将数组与链表结合使用
下面通过对HashMap源码分析来更好的了解HashMap的存储机制。

HashMap构造函数

在HashMap.java中可以看到有四个构造函数分别是:

 public HashMap() {        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);    }
 public HashMap(int initialCapacity) {        this(initialCapacity, DEFAULT_LOAD_FACTOR);    }
 public HashMap(int initialCapacity, float loadFactor) {        if (initialCapacity < 0)            throw new IllegalArgumentException("Illegal initial capacity: " +                                               initialCapacity);        if (initialCapacity > MAXIMUM_CAPACITY) {            initialCapacity = MAXIMUM_CAPACITY;        } else if (initialCapacity < DEFAULT_INITIAL_CAPACITY) {            initialCapacity = DEFAULT_INITIAL_CAPACITY;        }        if (loadFactor <= 0 || Float.isNaN(loadFactor))            throw new IllegalArgumentException("Illegal load factor: " +                                               loadFactor);        // Android-Note: We always use the default load factor of 0.75f.        // This might appear wrong but it's just awkward design. We always call        // inflateTable() when table == EMPTY_TABLE. That method will take "threshold"        // to mean "capacity" and then replace it with the real threshold (i.e, multiplied with        // the load factor).        threshold = initialCapacity;        init();    }

以上三个构造方法相信读者都能理解
下面重点说明上述三个构造方法中的参数
int initialCapacity: HashMap数据结构中存储的容量

initialCapacity的默认值 int DEFAULT_INITIAL_CAPACITY = 4

float loadFactor:负载因子,该参数决定HashMap中当存储数据为多少时,容器自动扩容。
loadFactor 默认值:float 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);        inflateTable(threshold);        putAllForCreate(m);    }

第四个构造函数本人目前使用较少,暂时不做详解。

HashMap内部实体类

HashMapEntry

   static class HashMapEntry<K,V> implements Map.Entry<K,V> {        final K key;        V value;        HashMapEntry<K,V> next;        int hash;        /**         * Creates new entry.         */        HashMapEntry(int h, K k, V v, HashMapEntry<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();        }        /**         * 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) {        }    }

着重了解HashMap内部实体类中当变量

K key:HashMap数据存储时 key值
V value:HashMap数据存储时value值
int hash:key的hashCode通过位运算生成的int值
HashMapEntry

HashMap 数据存储

put

 @Override public V put(K key, V value) {         if (table == EMPTY_TABLE) {            inflateTable(threshold);        }        if (key == null)            return putForNullKey(value);        int hash = sun.misc.Hashing.singleWordWangJenkinsHash(key);        int i = indexFor(hash, table.length);        for (HashMapEntry<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;    }

首先来确定该方法中的几个变量
EMPTY_TABLE:HashMapEntry

 private void inflateTable(int toSize) {        // Find a power of 2 >= toSize        int capacity = roundUpToPowerOf2(toSize);        // Android-changed: Replace usage of Math.min() here because this method is        // called from the <clinit> of runtime, at which point the native libraries        // needed by Float.* might not be loaded.        float thresholdFloat = capacity * loadFactor;        if (thresholdFloat > MAXIMUM_CAPACITY + 1) {            thresholdFloat = MAXIMUM_CAPACITY + 1;        }        threshold = (int) thresholdFloat;        table = new HashMapEntry[capacity];    }

在该方法内 可以看到主要是 通过int capacity = roundUpToPowerOf2(toSize); 来重新计算 capacity值,而该值是如何计算的?

private static int roundUpToPowerOf2(int number) {        // assert number >= 0 : "number must be non-negative";        int rounded = number >= MAXIMUM_CAPACITY                ? MAXIMUM_CAPACITY                : (rounded = Integer.highestOneBit(number)) != 0                    ? (Integer.bitCount(number) > 1) ? rounded << 1 : rounded                    : 1;        return rounded;    }

在roundUpToPowerOf2 方法内主要是通过Integer的两个静态方法highestOneBit,bitCount 来重新计算capacity值的
说明:
highestOneBit:
如果一个数是0, 则返回0
如果是负数, 则返回
-2147483648 1000,0000,0000,0000,0000,0000,0000,0000(二进制表示的数)
如果是正数, 返回的则是跟它最靠近的比它小的2的N次方
其实就是一句话, 返回最高位为1, 其它位为0的数

bitCount:给定一个int类型数据,返回这个数据的二进制串中“1”的总数量

通过上述两个方法可以看出当传入的 number 值为2的N次方时,返回该值,当不为2的N次方时,返回 number<<1
得到round值之后 继续看inflateTable 方法 ,在该方法内重新将
threshold 进行复制为 capacity * loadFactor ,同时new出一个新的table数组,该数组的大小为得到的capacity值。

当非第一次put或者

 if (table == EMPTY_TABLE) {            inflateTable(threshold);        }

上述三行代码已经执行完成之后

下面有分两种情况 当key为null以及key不为null时
1:当key == null时:

putForNullKey(value)
private V putForNullKey(V value) {        for (HashMapEntry<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;    }

当key== null时首先从table[0]中获取HashMapEntry对象,当该对象不为null时,判断该对象key是否为null,如果为null则将新传入的value覆盖掉oldValue,如果不为null,则获取该HashMapEntry中指向的下一个HashMapEntry对象,以此类推。

当table[0]位置HashMapEntry不存在或者 该位置中指向的下一个HashMapEntry都不存在key == null的情况下,modCount++ 并addEntry(0, null, value, 0);

void addEntry(int hash, K key, V value, int bucketIndex) {        if ((size >= threshold) && (null != table[bucketIndex])) {            resize(2 * table.length);            hash = (null != key) ? sun.misc.Hashing.singleWordWangJenkinsHash(key) : 0;            bucketIndex = indexFor(hash, table.length);        }        createEntry(hash, key, value, bucketIndex);    }

当size >= threshold && null != table[bucketIndex] 不成立时
可以看到直接之行了createEntry(hash, key, value, bucketIndex);

void createEntry(int hash, K key, V value, int bucketIndex) {        HashMapEntry<K,V> e = table[bucketIndex];        table[bucketIndex] = new HashMapEntry<>(hash, key, value, e);        size++;    }

在该方法中首先是获取了table[0]中当 HashMapEntry对象,同时新new出一个key为null的HashMapEntry对象,并其内部指向之前的HashMapEntry对象,同时将该key为null的对象放在table[0]位置
最后size++;
当size >= threshold && null != table[bucketIndex] 成立时

 resize(2 * table.length); hash = (null != key) ? sun.misc.Hashing.singleWordWangJenkinsHash(key) : 0; bucketIndex = indexFor(hash, table.length);

直接执行 resize()方法,而该方法的作用是扩充table数组。其内部执行代码:

void resize(int newCapacity) {        HashMapEntry[] oldTable = table;        int oldCapacity = oldTable.length;        if (oldCapacity == MAXIMUM_CAPACITY) {            threshold = Integer.MAX_VALUE;            return;        }        HashMapEntry[] newTable = new HashMapEntry[newCapacity];        transfer(newTable);        table = newTable;        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);    }

内部执行可以看到首先判断oldTable数组长度,当oldTable数组长度等于 MAXIMUM_CAPACITY 值时直接return;
当不满足时,重新new一个2倍oldTable长度的数组,并将该数组复制给table,同时重新复制threshold值。
在该段代码中另外注意到一个方法:
transfer(newTable);
而该方法的具体实现是:

 /**     * Transfers all entries from current table to newTable.     */    void transfer(HashMapEntry[] newTable) {        int newCapacity = newTable.length;        for (HashMapEntry<K,V> e : table) {            while(null != e) {                HashMapEntry<K,V> next = e.next;                int i = indexFor(e.hash, newCapacity);                e.next = newTable[i];                newTable[i] = e;                e = next;            }        }    }

可以看到该方法的具体作用是将当前数组中的内容copy到新的数组中。
到这里可以对于 resize()方法的分析已经玩车,紧接着看到内部开始执行:

 hash = (null != key) ? sun.misc.Hashing.singleWordWangJenkinsHash(key) : 0;

该行代码,在该行代码中可以看到主要目的是将key值转换为hash值,
在得到对应key值的hash值之后,继续执行

bucketIndex = indexFor(hash, table.length);

而该段代码的作用是通过key值生成的hash值& table.length重新生成一个int值,而该值则代表当前value所在的数组位置。

 static int indexFor(int h, int length) {        // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";        return h & (length-1);    }

至此当key为null时,putForNullKey(value)方法已经分析完成。
当key不为null,在put()方法中可以看到具体执行代码是:

int hash = sun.misc.Hashing.singleWordWangJenkinsHash(key);        int i = indexFor(hash, table.length);        for (HashMapEntry<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值获取到对应的hash值,通过indexFor()方法得到对应数组中的一个position,然后对该position位置进行遍历,如果该position或者该position的指向的下一个HashMapEntry中key值以及hash值是相同的那么就会用新的value替换旧的value,否则直接通过addEntry()方法将该key-value 存放到对应的数组中。

至此HashMap中对于数据的存放已经讲解完成,接下来看一下HashMap中是如何获取该value值。

get

 public V get(Object key) {        if (key == null)            return getForNullKey();        Entry<K,V> entry = getEntry(key);        return null == entry ? null : entry.getValue();    }

get方法很简单
当传入key为null时,直接之行getForNullKey()方法,该方法的具体实现是:

private V getForNullKey() {        if (size == 0) {            return null;        }        for (HashMapEntry<K,V> e = table[0]; e != null; e = e.next) {            if (e.key == null)                return e.value;        }        return null;    }

可以看出如果table size为0 则直接返回null,如果不为0 则直接遍历table[0] 位置的链表,当链表中某个位置的key为null 则直接将该位置HashMapEntry中的value返回,如果table[0]位置的链表中不存在key==null的情况,则直接返回null

当key不为null的情况下执行 getEntry(key)方法,改方法的具体实现:

final Entry<K,V> getEntry(Object key) {        if (size == 0) {            return null;        }        int hash = (key == null) ? 0 : sun.misc.Hashing.singleWordWangJenkinsHash(key);        for (HashMapEntry<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;    }

在该段代码中可以看到首先是通过key值以及table.length获取到该数据在table数组中的位置,同时通过该位置获取数组中对应的Entry数据,当Entry数据不为null的情况下,将Entry数据中的value值返回。

至此HashMap真对数据的put、get方法分析完成,各位看官如有疑问可以留言,或者自行通过HashMap源码进行分析。

0 0