数据结构---Java---HashMap---JDK1.7

Posted anpeiyong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构---Java---HashMap---JDK1.7相关的知识,希望对你有一定的参考价值。

 

 

源码解读

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable

     //*******内部类
     //Enrty<K,V> 单向链表
     static class Entry<K,V> implements Map.Entry<K,V> 
        final K key;
        V value;
        Entry<K,V> next;
        int hash;

        /**
         * Creates new entry.
         */
        Entry(int h, K k, V v, Entry<K,V> n) 
            value = v;
            next = n;
            key = k;
            hash = h;
        
     
      
     //*******属性
     static final Entry<?,?>[] EMPTY_TABLE = ;
     //Entry<K,V>[]数组实现
     transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
     final float loadFactor;
     static final float DEFAULT_LOAD_FACTOR = 0.75f;
     static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
     
     //*******构造器
     public HashMap() 
        this(DEFAULT_INITIAL_CAPACITY, 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;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);

        this.loadFactor = loadFactor;
        threshold = initialCapacity;
        init();
    

    public HashMap(int initialCapacity) 
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    

    //********方法
    //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);
        

     //put方法
     public V put(K key, V value) 
        
        //在put操作时,判断数组是否为空,再数组初始化容量
        if (table == EMPTY_TABLE) 
            inflateTable(threshold);
        
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);

        //定位数组索引i
        int i = indexFor(hash, table.length);

        //如果table[i]存在,然后使用单向链表解决冲突
        for (Entry<K,V> e = table[i]; e != null; e = e.next) 
            Object k;
 
            //如2个key 的hash值相等,并且  equals也相等,则覆盖旧值
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) 
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            
        

        modCount++;

        //如果table[i]没有,添加元素
        addEntry(hash, key, value, i);
        return null;
    

    //数组容量初始化
    private void inflateTable(int toSize) 
        // Find a power of 2 >= toSize
        int capacity = roundUpToPowerOf2(toSize);

        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        //根据计算容量初始化数组
        table = new Entry[capacity];
        initHashSeedAsNeeded(capacity);
    

    //定位数组索引i
    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);
    

    void addEntry(int hash, K key, V value, int bucketIndex) 
        if ((size >= threshold) && (null != table[bucketIndex])) 

            //扩容为原来的2倍
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        

        createEntry(hash, key, value, bucketIndex);
    

    //扩容
    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);
    


    //旧数组数据迁移至新数组(此处会引起  环形链表  )
    void transfer(Entry[] newTable, boolean rehash) 
        int newCapacity = newTable.length;

        //遍历旧数组中的每一项
        for (Entry<K,V> e : table) 
            while(null != e) 
                Entry<K,V> next = e.next;
                if (rehash) 
                    e.hash = null == e.key ? 0 : hash(e.key);
                
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = 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++;
    


    public V get(Object key) 
        if (key == null)
            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;
        

        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;
    

  

  

  

以上是关于数据结构---Java---HashMap---JDK1.7的主要内容,如果未能解决你的问题,请参考以下文章

在数据结构中数据、数据元素、数据对象、数据结构、存储结构、数据类型以及抽象数据类型的定义分别是啥

数据结构与数据类型有啥区别?

数据结构都有哪些

数据结构和数据类型的区别

数据结构哪些是四种常见的逻辑结构

数据结构基本概念