前言

这个也是一个老生畅谈的话题了,在大一的时候对概念比较模糊。现在将这个稍微记录一下来粗略讲一讲这两个的用处。
注意一点,重写equals方法一定要重写hashcode。equals相等hashcode一定相等,hashcode相等equals不一定相等。

正文


    @Test
    public void junit5Test() {
        Unit unit1 = new Unit("1", "1");
        Unit unit2 = new Unit("1", "1");
        Unit unit3 = new Unit("1", "2");
        Assertions.assertEquals(unit1, unit2);
        Assertions.assertEquals(unit1, unit3);
//        运行结果  第一个相当 第二个不相等
//        org.opentest4j.AssertionFailedError:
//        Expected :UtilTest.Unit(name=1, value=1)
//        Actual   :UtilTest.Unit(name=1, value=2)
    }

    @Test
    public void hasCodeTest() {
        HashSet<Unit> hashSet = new HashSet<>();
        long begin = System.currentTimeMillis();
        for (int i = 0; i < 30000; i++) {
            hashSet.add(new Unit("1", String.valueOf(i)));
        }
        long up = System.currentTimeMillis();
        System.out.println("set :" + (up - begin));
        hashSet.forEach(Unit::toString);
        long end = System.currentTimeMillis();
        System.out.println("one :" + (end - up));

//      result:
//        当 hashcode = return Objects.hash(name);
//        set :28420
//        one :15
//        当 hashcode = return Objects.hash(name, value);
//        set :10
//        one :13
//        由此可见 hashcode值在hash表创建索引起作用了
//        一般是根据hashcode找索引, 索引不存在直接添加, 索引存在比较是否相同, 相同不添加, 不同再找新位置添加
//        在下一个代码块展示一下 hash表中putValue的实现
    }

    @Data
    @AllArgsConstructor
    @ToString
    class Unit {
        String name;
        String value;

        /**
         * 通过 return 的比较来进行字段比较 相同则返回true
         * 所以可以通过 控制比较的字段数量来进行宽松的 还是严格的比较
         */
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Unit unit = (Unit) o;
            return Objects.equals(name, unit.name) &&
                    Objects.equals(value, unit.value);
        }

        /**
         * 产生 hash值 Object.hash(Object... values)
         * Object... values 表示可以传入多个值
         */
        @Override
        public int hashCode() {
            return Objects.hash(name, value);
        }
    }
}
    /**
     * 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 <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }	


	/**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    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;
    }