Java集合框架之HashMap源码分析(一):从hash方法演进之路看代码优化

1.7.0.17环境中默认构造HashMap中的时候会创建底层的数据结构,容量为16,同时计算出扩容需要的阈值12;而80年7月1日环境默认构造HashMap中的时候不创建底层的数据结构。

从哈希方法看linux下说的:“有品质的代码,重写代码,完美覆盖特例”。

jdk1.7.0.17的哈希方法:

/**
     * Retrieve object hash code and applies a supplemental hash function to the
     * result hash, which defends against poor quality hash functions.  This is
     * critical because HashMap uses power-of-two length hash tables, that
     * otherwise encounter collisions for hashCodes that do not differ
     * in lower bits. Note: Null keys always map to hash 0, thus index 0.
     */
    final int hash(Object k) {
        int h = 0;
        if (useAltHashing) {
            if (k instanceof String) {
                return sun.misc.Hashing.stringHash32((String) k);
            }
            h = hashSeed;
        }

        h ^= k.hashCode();

        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

jdk1.7.0.80的哈希方法:

/**
     * Initialize the hashing mask value. We defer initialization until we
     * really need it.
     */
    final boolean initHashSeedAsNeeded(int capacity) {
        boolean currentAltHashing = hashSeed != 0;
        boolean useAltHashing = sun.misc.VM.isBooted() &&
                (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
        boolean switching = currentAltHashing ^ useAltHashing;
        if (switching) {
            hashSeed = useAltHashing
                ? sun.misc.Hashing.randomHashSeed(this)
                : 0;
        }
        return switching;
    }

    /**
     * Retrieve object hash code and applies a supplemental hash function to the
     * result hash, which defends against poor quality hash functions.  This is
     * critical because HashMap uses power-of-two length hash tables, that
     * otherwise encounter collisions for hashCodes that do not differ
     * in lower bits. Note: Null keys always map to hash 0, thus index 0.
     */
    final int hash(Object k) {
        int h = hashSeed;
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }

        h ^= k.hashCode();

        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

 

从代码演进可以看出,1.7.0.80相比17版本,代码的优化简直就是极致,优雅。同时,这个JDK代码的优化完美的诠释了Linux的对于优雅代码的诠释。这就给我们今后优化代码指明了方向:重写代码,覆盖特例因此,可以总结出代码优化的思路:找出特例

 

 

 

    原文作者:java集合源码分析
    原文地址: https://blog.csdn.net/qq_21949545/article/details/80791142
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞