HashCode计算方法

1. String类型

String生成hashCode().

public int hashCode() {
        // The hash or hashIsZero fields are subject to a benign data race,
        // making it crucial to ensure that any observable result of the
        // calculation in this method stays correct under any possible read of
        // these fields. Necessary restrictions to allow this to be correct
        // without explicit memory fences or similar concurrency primitives is
        // that we can ever only write to one of these two fields for a given
        // String instance, and that the computation is idempotent and derived
        // from immutable state
        int h = hash;
        if (h == 0 && !hashIsZero) {
            h = isLatin1() ? StringLatin1.hashCode(value)
                           : StringUTF16.hashCode(value);// 根据编码来确定不同的生成方式
            if (h == 0) {
                hashIsZero = true;
            } else {
                hash = h;
            }
        }
        return h;
    }

其中StringLatin1的hashCode生成方式如下:

public static int hashCode(byte[] value) {
        int h = 0;
        for (byte v : value) {
            h = 31 * h + (v & 0xff);
        }
        return h;
    }

如value=“a”,则h=31*0+(97&1111 1111B)=97.


下面是String.equals()方法:

public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String aString = (String)anObject;
            if (!COMPACT_STRINGS || this.coder == aString.coder) {
                return StringLatin1.equals(value, aString.value);
            }
        }
        return false;
    }
  1. 首先==比较,==比较的就是地址值。
  2. 再比较字符串的内容,其调用StringLatin1.equals(),一个个遍历比较。
public static boolean equals(byte[] value, byte[] other) {
        if (value.length == other.length) {
            for (int i = 0; i < value.length; i++) {
                if (value[i] != other[i]) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

测试代码

public class TestHashCode {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		String a = "a";// 这几个对象具有相同地址
		String aa = "a";
		String b = "b";
		
		
		System.out.println("a".hashCode() == "a".hashCode());// true
		System.out.println(a.hashCode() == aa.hashCode());// true
		System.out.println(a.hashCode() == b.hashCode());// false
		
		System.out.println(a == aa);// true,说明地址相同
		System.out.println(a.equals(aa));// true
		System.out.println(a.equals(b));// false
		
	}
}

补充. HashMap.put()

/**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with {@code key}, or
     *         {@code null} if there was no mapping for {@code key}.
     *         (A {@code null} return can also indicate that the map
     *         previously associated {@code null} with {@code key}.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

对上面的注释,如果再put的key值已经再hashmap中存在,那么key对应的value值将会被覆盖。

其中第一个hash()函数如下

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

有道翻译注释部分

计算key.hashCode()并将(XORs)的散列值由高到低。由于表使用2的幂屏蔽,仅在当前屏蔽之上位变化的散列集将始终发生碰撞。(已知的例子有在小表中保存连续整数的浮点键集)因此我们应用了一种转换,将更高位的影响向下传播。比特传播的速度、效用和质量之间需要权衡。因为许多常见的散列集已经合理分布(所以不要受益于传播),因为我们用树来处理大型的碰撞在垃圾箱,我们只是XOR一些改变以最便宜的方式来减少系统lossage,以及将最高位的影响,否则永远不会因为指数计算中使用的表。

我的理解是:为了让高位更多的影响到低位,并且不浪费太多的计算资源,所以采用该方式。

接下来是putVal()

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
  1. 首先判断table,也就是存储Envey对的表是否非空。
  2. 再将传进来的hash值进行AND运算,来给这个新元素分配一个位置。如果hash>(table.length-1),那么要把这个新加入的元素放在表的最后,如length=4,hash=5,5>(4-1),所以将hash=5的值放在table[3]的位置。
  3. 再判断新加入的元素是否是分配table位置的首元素。如果是,则不加入;如果不是,加入树中,用于查找方便。
  4. 如果key在加入前存在value值,则返回value值。

Hashtable.put()

public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();// hash值=hashCode值
        int index = (hash & 0x7FFFFFFF) % tab.length;// 放在table中的那个下标
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }

        addEntry(hash, key, value, index);
        return null;
    }

下面是上方的addEntry()

private void addEntry(int hash, K key, V value, int index) {
        Entry<?,?> tab[] = table;
        if (count >= threshold) {
            // Rehash the table if the threshold is exceeded
            rehash();

            tab = table;
            hash = key.hashCode();
            index = (hash & 0x7FFFFFFF) % tab.length;
        }

        // Creates the new entry.
        @SuppressWarnings("unchecked")
        Entry<K,V> e = (Entry<K,V>) tab[index];
        tab[index] = new Entry<>(hash, key, value, e);// 加在链表头
        count++;
        modCount++;
    }

Hashtable的hash值确实是对象的hashCode()值。可以对比上方HashMap.put()中的hash()方法

return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);

Hashtable和HashMap对比

  1. resize
    Hashtable通过

    int newCapacity = (oldCapacity << 1) + 1;
    resize容量大小。

    而HashMap.resize()中

if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold

可以推知,容量(capability)和警戒线(Threshold)都变为两倍。

总结

  1. String的hash值是通过每个字符计算得到的,并不是地址。相同字符的String有相同的hashCode值。
  2. HashMap.put()一个值,会先根据key值计算hash(key),再根据这个hash(key)来决定加到table的哪个位置。

参考

  1. Hashtable和HashMap区别详解
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值