HashMap,HashTable,TreeMap,ConcurrentHashMap源码级总结!

最近面试面了不少了,总是被问到HashMap,有问HashMap和TreeMap区别的,有问HashMap和LinkedList区别的各种,反正就是排列组合。于是就搜集了一下,结合自己的理解,进行一下总结。如有错漏还请在评论区帮忙指出!

看总结直接拉到底。

 

还未了解的部分:各集合的迭代器。序列化接口部分。

 

hash值和hashCode:

Java令所有数据类型都继承了一个能够返回32比特整数hashCode()方法。

每一种数据类型的hashCode方法必须与equals方法一致。

hashCode与equals的关系不再详述了。

String的hashCode():

private final char value[];
/**
     * Returns a hash code for this string. The hash code for a
     * {@code String} object is computed as
     * <blockquote><pre>
     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     * </pre></blockquote>
     * using {@code int} arithmetic, where {@code s[i]} is the
     * <i>i</i>th character of the string, {@code n} is the length of
     * the string, and {@code ^} indicates exponentiation.
     * (The hash value of the empty string is zero.)
     *
     * @return  a hash code value for this object.
     */
public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

从注释里可以看到,String的hashCode返回的为:

s[0]*31^(n-1) + s[1]*31^[n-1] + ... + s[n-1]      (这里的^是乘方的意思,与后面的按位异或不要搞混)

例子:一个String s = "123";

它的hashCode为: '1' * 31^(3-1) + '2' * 31^(3-2) + '3' * 31^(3-3)

这里char需转为int。可以计算出hashCode为48690。

另外,可以去查看一下源码,会发现Integer的hashCode就是它的值。

为什么这样:

散列表希望hashCode()方法能够将键平均地散布为所有可能的32位整数。

取31。主要是因为31是一个奇质数,所以31i=32i-i=(i<<5)-i,这种位移与减法结合的计算相比一般的运算快很多。

但是在HashMap中并不是直接使用的hashCode()所产生的值来作为索引的。且看下段代码:

 /**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

这段代码的意思是:(摘自)

hashmap中要找到某个元素,需要根据key的hash值来求得对应数组中的位置.
key的hash值高16位不变,低16位与高16位异或作为key的最终hash值。(h >>> 16,表示无符号右移16位,高位补0,任何数跟0异或都是其本身,因此key的hash值高16位不变。)

 

为什么要这样呢?连接里的文章有说,但我没看明白。思想大概就是使碰撞的概率最小。

其他的,比如HashTable里的hash计算方法是不一样的,具体看源码就行了。

 

HashMap:

从源码中可以看到,HashMap继承了AbstractMap类(一个抽象类),然后AbstractMap又实现了Map接口。

HashMap本身也有hashCode方法,是是现在AbstractMap里的,就是把所有Node的hashCode加起来了。

    public int hashCode() {
        int h = 0;
        Iterator<Entry<K,V>> i = entrySet().iterator();
        while (i.hasNext())
            h += i.next().hashCode();
        return h;
    }

而Node的hashCode怎么计算呢?就是把key和value的hashCode按位异或一下。

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

HashMap的MAXIMUM_CAPACITY 为 1<<30,也就是2的30次方。

HashMap的DEFAULT_LOAD_FACTOR为0.75。

HashMap的default initial capacity为16。扩容时候翻倍

HashMap的构造器有四种,分别是 默认,可以改initialCapacity,可以改loadFactor和initialCapactiy,在构造时直接创建一个Node。

HashMap的get(),containsKey()等,都用到了getNode ()方法。

/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;

final Node<K,V> getNode(int hash, Object key) {
        N
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值