共同学习Java源代码-数据结构-HashMap(二)

来源:互联网 发布:java web入门书籍推荐 编辑:程序博客网 时间:2024/05/24 06:15

    static class Node<K,V> implements Map.Entry<K,V> {

这个类就是键值对的实现类,实现了Map接口的内部接口Entry

        final int hash;

这个成员变量是hash值。

        final K key;

这个成员变量是键。

        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;
        }
构造方法就是初始化所有成员变量。

        public final K getKey()        { return key; }

        public final V getValue()      { return value; }

getter方法。

        public final String toString() { return key + "=" + value; }
toString方法。

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }
hashCode方法。返回的是键的hashCode和值得hashCode的异或值。

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }
这个是给值赋值的方法。

        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;

        }

这个是equals方法。判断过程比较简单,就是先判断是否是同一对象,然后判断是否是同一个实现类,然后判断每个键和值分别相等。

    }


0 0
原创粉丝点击