JDK源码之HashMap源码解析

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDK源码之HashMap源码解析相关的知识,希望对你有一定的参考价值。

HashMap 源码解析

首先看一下树节点构造

static final class Entry<K,V> implements Map.Entry<K,V> {
        K key;
        V value;
        Entry<K,V> left;
        Entry<K,V> right;
        Entry<K,V> parent;
        boolean color = BLACK;

        /**
         * Make a new cell with given key, value, and parent, and with
         * {@code null} child links, and BLACK color.
         */
        Entry(K key, V value, Entry<K,V> parent) {
            this.key = key;
            this.value = value;
            this.parent = parent;
        }

        /**
         * Returns the key.
         *
         * @return the key
         */
        public K getKey() {
            return key;
        }

        /**
         * Returns the value associated with the key.
         *
         * @return the value associated with the key
         */
        public V getValue() {
            return value;
        }

        /**
         * Replaces the value currently associated with the key with the given
         * value.
         *
         * @return the value associated with the key before this method was
         *         called
         */
        public V setValue(V value) {
            V oldValue = this.value;
            this.value = value;
            return oldValue;
        }

        public boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;

            return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
        }

        public int hashCode() {
            int keyHash = (key==null ? 0 : key.hashCode());
            int valueHash = (value==null ? 0 : value.hashCode());
            return keyHash ^ valueHash;
        }

        public String toString() {
            return key + "=" + value;
        }
    }

一个节点由key,value对(TreeMap),左子节点,右子节点,父亲节点,标志位color,红黑树只有2种颜色(red,black)组成。节点初始化的时候默认为Black。
树节点比较函数:

public boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;

            return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
        }

首先类型比较,然后key,value分别进行比较

以上是关于JDK源码之HashMap源码解析的主要内容,如果未能解决你的问题,请参考以下文章

JDK源码解析-HashMap

jdk1.7源码之-hashMap源码解析

Java中的容器(集合)之HashMap源码解析

Map源码解析之HashMap源码分析

jdk1.8源码解析:HashMap底层数据结构之链表转红黑树的具体时机

Java 集合系列10之 HashMap详细介绍(源码解析)和使用示例