HashMap.Node source code

 The internal class of HashMap, used to store the node data on the linked list

    // 内部类,重新实现map的Entry接口
    static class Node<K,V> implements Map.Entry<K,V> {
    	// 存入hash值
        final int hash;
        // 存入key
        final K key;
        // 存入value
        V value;
        // 存入下一个节点位置
        Node<K,V> next;
        
        // 构造
        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }
        
        // 获取当前的key
        public final K getKey()        { return key; }
        // 获取当前的value
        public final V getValue()      { return value; }
        // 重写toString方法
        public final String toString() { return key + "=" + value; }
        // 计算hashCode值
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }
        // 重新设置当前entry的值
        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }
        // 比较两个entry
        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

 

Guess you like

Origin blog.csdn.net/qq_26896085/article/details/105090467