HashMap 高度解析

参考:http://blog.sina.com.cn/s/blog_790f47850101bzd5.html

HashMap主要是用数组来存储数据的,我们都知道它会对key进行哈希运算,哈系运算会有重复的哈希值,对于哈希值的冲突,HashMap采用链表来解决的。

  

public HashMap(int capacity, float loadFactor) {
        this(capacity);

        if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
            throw new IllegalArgumentException("Load factor: " + loadFactor);
        }

        /*
         * Note that this implementation ignores loadFactor; it always uses
         * a load factor of 3/4. This simplifies the code and generally
         * improves performance.
         */
    }

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、 public HashMap(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity: " + capacity); } if (capacity == 0) { @SuppressWarnings("unchecked") HashMapEntry<K, V>[] tab = (HashMapEntry<K, V>[]) EMPTY_TABLE; table = tab; threshold = -1; // Forces first put() to replace EMPTY_TABLE return; } if (capacity < MINIMUM_CAPACITY) { capacity = MINIMUM_CAPACITY; } else if (capacity > MAXIMUM_CAPACITY) { capacity = MAXIMUM_CAPACITY; } else { capacity = Collections.roundUpToPowerOfTwo(capacity); } makeTable(capacity); }

 

capacity 指定容量 注意:输入n 找到2的几次方中大于n最小值走位容量值
loadFactor 加载因子:默认0.75

当实际数据大小超过threshold时,HashMap会将容量扩容,threshold=容量*加载因子

参考:http://alex09.iteye.com/blog/539545

1.key 根据 key的hashcode值寻找 table位置,寻找方法 相当于模除table大小。位置上有元素 则连表追加
2.有一个默认的负载因子(load factor),其默认值为 0.75,这是时间和空间成本上一种折衷:增大负载因子可以减少 Hash 表(就是那个 Entry 数组)所占用的内存空间,但会增加查询数据的时间开销,而查询是最频繁的的操作(HashMap 的 get() 与 put() 方法都要用到查询);减小负载因子会提高数据查询的性能,但会增加 Hash 表所占用的内存空间。

 

 


posted on 2015-04-16 20:08  wjw334  阅读(175)  评论(0编辑  收藏  举报

导航