您的位置:首页 > 编程语言 > Java开发

Java记录 -71- HashMap源码剖析

2017-07-01 16:01 369 查看
HashMap底层维护着一个数组,我们向HashMap中所放置的对象实际上是存储在该数组当中。数组中每个元素都维护着一个链表,每个链表中的所有元素的hash值都一样。
HashMap的四个构造方法:
底层维护的数组 Entry[] table,数组默认大小为16,并为2的整数次幂;

底层数组存放的Entry对象,是HashMap的一个内部类,包含了key,value和next变量;

[code=java;toolbar:false">   /**    * The table, resized as necessary. Length MUST Always be a power of two.    */   transient Entry[] table;   static class Entry<K,V> implements Map.Entry<K,V> {        final K key;        V value;        Entry<K,V> next;        final int hash;        ......    }       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();    }    public HashMap(int initialCapacity) {        this(initialCapacity, DEFAULT_LOAD_FACTOR);    }    public HashMap() {        this.loadFactor = DEFAULT_LOAD_FACTOR;        threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);        table = new Entry[DEFAULT_INITIAL_CAPACITY];        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);        putAllForCreate(m);    }

下面来看做关心的添加方法put:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: