Java集合-HashMap

来源:互联网 发布:淘宝假酒处罚规定 编辑:程序博客网 时间:2024/05/19 09:37

HashMap源码中用到的几种运算符

>>>:右移,带符号的

^:按位异或

&:逻辑与


声明JDK的版本1.7


HashMap的存储结构是数组+链表。HashMap添加键值对的时候添加的是Entrty对象,Entrty对象保存了key,value和next(也就是Entrty)对象。其中Entrty类是HashMap的内部类。


HashMap put一个键值对的时候的源码流程:

put函数大致的思路为:

  1. 对key的hashCode()做hash,然后再计算index;
  2. 如果没碰撞直接放到bucket里;
  3. 如果碰撞了,以链表的形式存在buckets后;
  4. 如果碰撞导致链表过长(大于等于TREEIFY_THRESHOLD),就把链表转换成红黑树;//这个好像是jdk1.8里的
  5. 如果节点已经存在就替换old value(保证key的唯一性)
  6. 如果bucket满了(超过load factor*current capacity),就要resize。

    public V put(K key, V value) {        if (table == EMPTY_TABLE) {            inflateTable(threshold);        }        if (key == null)            return putForNullKey(value); //如果key为null        int hash = hash(key);//获取key的hash值        int i = indexFor(hash, table.length);//根据hash值获取存储的索引        for (Entry<K,V> e = table[i]; e != null; e = e.next) {//根据i,找到当前链表并且遍历            Object k;                       // hash值相等并且key也想等,则认为是同一个key,把原来的value替换掉            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);//如果key不相等,则把新的Entrty对象添加至数组中        return null;    }

重点来看addEntrty方法:

    void addEntry(int hash, K key, V value, int bucketIndex) {        //如果容量不够,就根据loadFactor扩大数组容量到原来的1.5倍和ArrayList一样,同时根据数组长度重新计算hash和index值        if ((size >= threshold) && (null != table[bucketIndex])) {            resize(2 * table.length);            hash = (null != key) ? hash(key) : 0;            bucketIndex = indexFor(hash, table.length);        }        //创建新的Entrty对象并添加至数组中        createEntry(hash, key, value, bucketIndex);    }   //如果该位置有元素,则当前Entrty的next指向它,否则为空  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++;  }

每次put一个元素到HashMap中,都new一个Node对象,位置是通过计算key的hash值来确定。如果两个元素有相同的hash值,它们会被放在同一个索引上。原来它是以链表(LinkedList)的形式来存储的。上面已经详细讲过了!!!


//key的hash值得计算方法

    final int hash(Object k) {        int h = hashSeed;        if (0 != h && k instanceof String) {            return sun.misc.Hashing.stringHash32((String) k);        }        h ^= k.hashCode();        // This function ensures that hashCodes that differ only by        // constant multiples at each bit position have a bounded        // number of collisions (approximately 8 at default load factor).        h ^= (h >>> 20) ^ (h >>> 12);        return h ^ (h >>> 7) ^ (h >>> 4);    }

//计算索引位置,所以不同的hash值,得到的索引也有可能是相同的。

    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);    }

HashMap get的源码流程:

    public V get(Object key) {        if (key == null)            return getForNullKey();        Entry<K,V> entry = getEntry(key);        return null == entry ? null : entry.getValue();    }
关键是看getentrty()方法:

    final Entry<K,V> getEntry(Object key) {        if (size == 0) {            return null;        }        int hash = (key == null) ? 0 : hash(key);//这里同样是用key获取hash值,并找到相应的index位置        for (Entry<K,V> e = table[indexFor(hash, table.length)];             e != null;             e = e.next) {            Object k;            //hash值相等,并且key也相等,就返回Entrty对象,否则返回null。完美的回答!!!            if (e.hash == hash &&                ((k = e.key) == key || (key != null && key.equals(k))))                return e;        }        return null;    }


1 0