hashmap原理分析

2019-10-20  本文已影响0人  后来丶_a24d

目录

目录.png

构造器

 this.threshold = tableSizeFor(initialCapacity);
 static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

确定哈希桶数据索引位置

static int indexFor(int h, int length) {  
      return h & (length-1); 
 }

补充:二进制的按位与运算举例:23 & 15 = 7
0 1 0 1 1 1
0 0 1 1 1 1    
-------------
0 0 0 1 1 1

HashMap的put方法实现

hashmap的get方法

hashmap的扩容

初始化部分

已有数组扩容

既然红黑树那么好,为啥hashmap不直接采用红黑树,而是当大于8个的时候才转换红黑树?

Hashmap为什么不用平衡树

解决hash冲突的办法

hashmap为何线程不安全

hashmap排序高级用法

ArrayList<Integer> list = new ArrayList<>(hashMap.keySet());
//调用sort方法并重写比较器进行升/降序
Collections.sort(list, (o1, o2) -> o1> o2 ? 1 : 0);

Iterator<Integer> iterator = list.iterator();
//迭代排序后的key的list
while ((iterator.hasNext())){
    Integer key = iterator.next();
    String value = hashMap.get(key);
    System.out.print(key+"="+value+",");
}
ArrayList<Map.Entry<Integer,String>> list = new ArrayList<>(hashMap.entrySet());
// Comparator升序
Collections.sort(list, Map.Entry.comparingByValue());
Iterator<Map.Entry<Integer,String>> iterator = list.iterator();
for(Map.Entry<Integer,String> m : list){
    System.out.println(m.getKey()+"="+m.getValue());
}

参考文献

上一篇 下一篇

猜你喜欢

热点阅读