首页 > 编程语言 >河北王校长源码之HashMap

河北王校长源码之HashMap

时间:2024-03-14 20:26:16浏览次数:24  
标签:return HashMap int value 源码 key hash null 校长

HashMap

类结构

  • 继承AbstractMap<K,V>
  • 实现Map<K,V>
    • Map基本方法
  • 实现Cloneable
    • 浅克隆
  • 实现Serializable
    • 序列化

成员变量

    // 默认初始化容量
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 
    // 数组最大长度
    static final int MAXIMUM_CAPACITY = 1 << 30;
    // 默认负载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    // 转树阈值
    static final int TREEIFY_THRESHOLD = 8;
    // 解树阈值(考虑解树性能,变为7时无需变化红黑树;留有缓冲,懒处理)
    static final int UNTREEIFY_THRESHOLD = 6;
    // 最小树容量
    static final int MIN_TREEIFY_CAPACITY = 64;
    transient Node<K,V>[] table;
    transient Set<Map.Entry<K,V>> entrySet;
    transient int size;
    transient int modCount;
	// 容量阈值
    int threshold;
	// 负载因子
    final float loadFactor;

数据结构

	static class Node<K,V> implements Map.Entry<K,V> {
        // 内存地址不可改变
        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; }
        public final String toString() { return key + "=" + value; }
        // 键值分别异或得到结点hash值
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        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) {
                // o属于Map.Entry,进行泛型强转
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                // 使用objects.equals进行综合判断
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }
	interface Entry<K,V> {
        K getKey();
        V getValue();
        V setValue(V value);
        boolean equals(Object o);
        int hashCode();
        // 返回一个基于键进行比较的比较器。比较器会根据键的自然顺序进行比较
        public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> c1.getKey().compareTo(c2.getKey());
        }
        // 返回一个基于值进行比较的比较器。比较器会根据值的自然顺序进行比较
        public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> c1.getValue().compareTo(c2.getValue());
        }
        // 返回一个基于键进行比较的比较器,使用给定的自定义比较器来比较键
        public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
            Objects.requireNonNull(cmp);
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
        }
        // 返回一个基于值进行比较的比较器,使用给定的自定义比较器来比较值
        public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
            Objects.requireNonNull(cmp);
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
        }
    }

静态方法

哈希方法

	// 通过将哈希码的高位与低位进行混合,可以更好地充分利用哈希码的信息,提高哈希函数的散列效果和键值的均匀分布
	static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

比较方法

    // 通过类型检查和反射获取实现了 Comparable 接口且泛型参数为对应类的类对象
	static Class<?> comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class<?> c; 
            Type[] ts, as;
            Type t;
            // 泛型接口,可以返回泛型的实际类型、原始类型、拥有者类型
            ParameterizedType p;
            // 放行string类型
            if ((c = x.getClass()) == String.class)
                return c;
            // c实现的接口数组不为空
            if ((ts = c.getGenericInterfaces()) != null) {
                for (int i = 0; i < ts.length; ++i) {
                    // 判断每个接口t是否为泛型接口,且原始类型为 Comparable,且泛型参数列表长度为 1,且第一个泛型参数为 c
                    // Comparable<String>
                    if (((t = ts[i]) instanceof ParameterizedType) &&
                        ((p = (ParameterizedType)t).getRawType() == Comparable.class) &&
                        (as = p.getActualTypeArguments()) != null && as.length == 1 && as[0] == c) 
                        return c;
                }
            }
        }
        return null;
    }
	// 比较对象大小,无法比较返回0
    static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }

容量计算方法

    // 将传入的大小调整为比 cap 大且是 2 的幂次方的最小整数
	static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

普通方法

构造方法

    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
        this.loadFactor = loadFactor;
        // 向上取整2的N次
        this.threshold = tableSizeFor(initialCapacity);
    }

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; 
    }

    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }
	final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            // hashmap尚未初始化,计算容量,对容量阈值赋值
            if (table == null) { 
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            // 已经初始化且大小不足,进行扩容
            else if (s > threshold)
                resize();
            // 遍历指定 Map 中的每个元素,将其键(key)和值(value)通过调用 putVal 方法放入当前 HashMap 中
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

获取方法

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    final Node<K,V> getNode(int hash, Object key) {
        // tab 表示哈希表的数组,first 表示哈希桶中的第一个节点,e 表示遍历哈希桶时的当前节点,n 表示哈希表的长度,k 表示节点的键
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        // 判断哈希表数组 tab 不为 null、哈希表长度 n 大于 0,并且对应的哈希桶中的第一个节点 first 不为 null
        if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
            // 首结点匹配
            // 第一个节点 first 的哈希值和给定的哈希值 hash 相等,同时键 key 和节点的键 k 相等(或者都为 null)
            if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                // 红黑树进行相应的处理
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                // 进入一个循环遍历,从第一个节点 first 开始,逐个比较节点的哈希值和键,直到找到匹配的节点或遍历结束
                do {
                    if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

设置方法

通过方法返回值对key唯一性进行校验

针对已经写入hashmap,可以将旧值重新写入

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
	// 不替换相同的值
    public V putIfAbsent(K key, V value) {
        return putVal(hash(key), key, value, true, true);
    }
	// 先添加后扩容
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 检查当前的哈希表(table)是否已经存在,如果不存在或长度为0,则进行扩容操作
        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);
                        // 链表长度大于等于8,变为树
                        if (binCount >= TREEIFY_THRESHOLD - 1) 
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 找到了相同的节点,则直接退出遍历
                    if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    // 链表移动
                    p = e;
                }
            }
            // 对存在的相同结点,进行值的替换
            if (e != null) { 
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                // 为linkedHshmap设置的方法
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // 容量大于阈值,扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

扩容方法

    final Node<K,V>[] resize() {
        // 旧hash表
        Node<K,V>[] oldTab = table;
        // 旧容量 16
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        // 旧阈值 12
        int oldThr = threshold;
        // 新容量,新阈值
        int newCap, newThr = 0;
        if (oldCap > 0) {
            // 旧的数组容量 >0 的情况下
            // 旧容量已经达到了最大容量MAXIMUM_CAPACITY,直接设置阈值为Integer.MAX_VALUE,放弃扩容
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 容量翻一倍且符合条件的情况下 阈值也翻一倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; 
        }
        // 旧的数组容量 <=0 且旧的阈值 >0,就把新的容量设置成旧的阈值
        else if (oldThr > 0)
            newCap = oldThr;
        // 旧的数组容量 <=0 且旧的阈值 <0,就重新设置新的长度和阈值为默认值
        else {               
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        // 新的阈值为0,就重新根据新的容量设置阈值
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE);
        }
        
        // 扩容因子赋值替换
        threshold = newThr;
        // 根据新的长度初始化新的数组并替换
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        
        if (oldTab != null) {
            // 遍历旧的节点数组
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    // 链表不存在,直接赋值
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    // 树节点特殊处理
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    // 链表结点
                    else {
                        // 低位链表:存放在扩容之后的数组的下标位置,与当前数组下标位置一致
                        // loHead: 低位链表头节点
                        // loTail: 低位链表尾节点
                        Node<K,V> loHead = null, loTail = null;
                        // 高位链表,存放扩容之后的数组的下标位置,原索引+扩容之前数组容量
                        // hiHead: 高位链表头节点
                        // hiTail: 高位链表尾节点
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            // 位置不变
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            // 当前位置+旧容量
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        // 转移到新数组
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

树化方法

    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        // 数组容量小于64,扩容
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        // 数组已经初始化且容量大于等于64
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            // 红黑树的头节点和尾节点指针
            TreeNode<K,V> hd = null, tl = null;
            do {
                // 将槽位第一个元素转化为链表节点
                TreeNode<K,V> p = replacementTreeNode(e, null);
                // 尾节点为空表示首次进入,将当前结点赋值给头节点
                if (tl == null)
                    hd = p;
                // 红黑树已经存在,将当前元素p作为尾结点指向的元素
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                // 尾结点更新为最后一个节点
                tl = p;
            } while ((e = e.next) != null);
            // 树化操作
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }
    TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
        // next存在
        // 1.TreeNode为Node子类
        // 2.方便解树
        return new TreeNode<>(p.hash, p.key, p.value, next);
    }

删除方法

    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value;
    }
    public boolean remove(Object key, Object value) {
        return removeNode(hash(key), key, value, true, true) != null;
    }
	final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
       	// 数组初始化完成 且 有值 且 该hash位置有值
        if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            // 第一个节点的哈希值和键与参数hash和key匹配,则将第一个节点p赋值给node
            if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            // 不匹配且存在后续节点
            else if ((e = p.next) != null) {
                // 树节点查找
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                // 循环遍历节点,匹配到将节点赋值给node
                else {
                    do {
                        if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            // 被删除节点已经被找到
            if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                // 移除头节点,槽位直接指向node的下一个节点
                else if (node == p)
                    tab[index] = node.next;
                // 跳过p节点,将p的next指针指向node的下一个节点
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

清理方法

    public void clear() {
        Node<K,V>[] tab;
        modCount++;
        if ((tab = table) != null && size > 0) {
            size = 0;
            // 清空槽位
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null;
        }
    }

存在判断方法

    public boolean containsValue(Object value) {
        Node<K,V>[] tab; V v;
        // 数组已经初始化且存在数据
        if ((tab = table) != null && size > 0) {
            // 遍历数组
            for (int i = 0; i < tab.length; ++i) {
                // 遍历节点
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    // 值相同
                    if ((v = e.value) == value || (value != null && value.equals(v)))
                        return true;
                }
            }
        }
        return false;
    }

键集合方法

并未维护一个set集合,而是做了映射处理,keyset相等于hashmap的视图

实现原理:

  1. 增强for操作基于迭代器实现
    • 迭代器iterator()方法依赖于KeyIterator类
    • KeyIterator继承HashIterator,返回nextNode().key
      • KeyIterator无构造,会调用HashIterator类构造,获取hashmap的table结构
      • 调用nextNode().key进一步获取数据
  2. 其余操作基于hashmap结构实现
  3. 打印操作默认调用tostring()
    • keyset继承AbstractSet继承AbstractCollection的tostring()方法,内部使用迭代器
    public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new KeySet();
            keySet = ks;
        }
        return ks;
    }

    final class KeySet extends AbstractSet<K> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<K> iterator()     { return new KeyIterator(); }
        public final boolean contains(Object o) { return containsKey(o); }
        public final boolean remove(Object key) {
            return removeNode(hash(key), key, null, false, true) != null;
        }
        public final Spliterator<K> spliterator() {
            return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super K> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.key);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }
    final class KeyIterator extends HashIterator
        implements Iterator<K> {
        public final K next() { return nextNode().key; }
    }
    abstract class HashIterator {
        Node<K,V> next;        // next entry to return
        Node<K,V> current;     // current entry
        int expectedModCount;  // for fast-fail
        int index;             // current slot

        HashIterator() {
            expectedModCount = modCount;
            Node<K,V>[] t = table;
            current = next = null;
            index = 0;
            if (t != null && size > 0) { // advance to first entry
                do {} while (index < t.length && (next = t[index++]) == null);
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Node<K,V> nextNode() {
            Node<K,V>[] t;
            Node<K,V> e = next;
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            // 无后续节点 且 数组存在,进行槽位切换
            if ((next = (current = e).next) == null && (t = table) != null) {
                do {} while (index < t.length && (next = t[index++]) == null);
            }
            // 直接链表移动
            return e;
        }

        public final void remove() {
            Node<K,V> p = current;
            if (p == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            current = null;
            K key = p.key;
            removeNode(hash(key), key, null, false, false);
            expectedModCount = modCount;
        }
    }

值集合方法

    public Collection<V> values() {
        Collection<V> vs = values;
        if (vs == null) {
            vs = new Values();
            values = vs;
        }
        return vs;
    }

    final class Values extends AbstractCollection<V> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<V> iterator()     { return new ValueIterator(); }
        public final boolean contains(Object o) { return containsValue(o); }
        public final Spliterator<V> spliterator() {
            return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super V> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.value);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

键值对集合

   public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }

    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator();
        }
        public final boolean contains(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry<?,?> e = (Map.Entry<?,?>) o;
            Object key = e.getKey();
            Node<K,V> candidate = getNode(hash(key), key);
            return candidate != null && candidate.equals(e);
        }
        public final boolean remove(Object o) {
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>) o;
                Object key = e.getKey();
                Object value = e.getValue();
                return removeNode(hash(key), key, value, true, true) != null;
            }
            return false;
        }
        public final Spliterator<Map.Entry<K,V>> spliterator() {
            return new EntrySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                for (int i = 0; i < tab.length; ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }

替换方法

    public boolean replace(K key, V oldValue, V newValue) {
        Node<K,V> e; V v;
        // key hash oldValue相同进行替换
        if ((e = getNode(hash(key), key)) != null &&
            ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
            e.value = newValue;
            afterNodeAccess(e);
            return true;
        }
        return false;
    }
    public V replace(K key, V value) {
        Node<K,V> e;
        // key hash 相同进行替换
        if ((e = getNode(hash(key), key)) != null) {
            V oldValue = e.value;
            e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
        return null;
    }

克隆方法

    public Object clone() {
        HashMap<K,V> result;
        try {
            // 浅拷贝
            result = (HashMap<K,V>)super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
        result.reinitialize();
        result.putMapEntries(this, false);
        return result;
    }
    void reinitialize() {
        table = null;
        entrySet = null;
        keySet = null;
        values = null;
        modCount = 0;
        threshold = 0;
        size = 0;
    }
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

序列化方法

    private void writeObject(java.io.ObjectOutputStream s)
        throws IOException {
        int buckets = capacity();
        s.defaultWriteObject();
        s.writeInt(buckets);
        s.writeInt(size);
        internalWriteEntries(s);
    }
    void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
        Node<K,V>[] tab;
        if (size > 0 && (tab = table) != null) {
            // 遍历槽位
            for (int i = 0; i < tab.length; ++i) {
                // 遍历节点
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    s.writeObject(e.key);
                    s.writeObject(e.value);
                }
            }
        }
    }
    private void readObject(java.io.ObjectInputStream s)
        throws IOException, ClassNotFoundException {
        s.defaultReadObject();
        reinitialize();
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new InvalidObjectException("Illegal load factor: " +
                                             loadFactor);
        s.readInt();             
        int mappings = s.readInt();
        if (mappings < 0)
            throw new InvalidObjectException("Illegal mappings count: " +
                                             mappings);
        else if (mappings > 0) { 
            float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f);
            float fc = (float)mappings / lf + 1.0f;
            int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ?
                       DEFAULT_INITIAL_CAPACITY :
                       (fc >= MAXIMUM_CAPACITY) ?
                       MAXIMUM_CAPACITY :
                       tableSizeFor((int)fc));
            float ft = (float)cap * lf;
            threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ?
                         (int)ft : Integer.MAX_VALUE);
            SharedSecrets.getJavaOISAccess().checkArray(s, Map.Entry[].class, cap);
            @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] tab = (Node<K,V>[])new Node[cap];
            table = tab;
            for (int i = 0; i < mappings; i++) {
                @SuppressWarnings("unchecked")
                    K key = (K) s.readObject();
                @SuppressWarnings("unchecked")
                    V value = (V) s.readObject();
                // 数据复位
                putVal(hash(key), key, value, false, false);
            }
        }
    }

槽点

  • 继承AbstractMap情况下,依旧实现Map接口
  • put判断结点是否到8进行扩容时,存在歧义

参考链接

标签:return,HashMap,int,value,源码,key,hash,null,校长
From: https://www.cnblogs.com/faetbwac/p/18073172

相关文章

  • 河北王校长源码之ArrayList
    ArrayListy类结构继承AbstractList实现Listlist基本方法实现RandomAccess支持随机访问(下标)for效率高于迭代器(对比LinkedList)实现Cloneable浅克隆实现Serializable序列化成员变量默认容量privatestaticfinalintDEFAULT_CAPACITY=10;空数组......
  • Linux源码安装nginx1.20.2
    下面是关于Linux源码安装nginx1.20.2的操作流程目录前言1,安装准备1.1下载安装包 1.2上传安装包1.3解压  1.4关闭防火墙和selinux2,安装 nginx依赖库以及编译环境2.1安装nginx依赖库 2.2执行configure脚本生成makefile配置文件2.2.1可能出现的错误 3,......
  • PG14:auth_delay 插件源码分析
    auth_delay让服务器在报告身份验证失败前短暂暂停,以增加对数据库密码进行暴力破解的难度。需要注意的是,这对阻止拒绝服务攻击毫无帮助,甚至可能加剧攻击,因为在报告身份验证失败前等待的进程仍会占用连接。要使用这个模块必须要在postgresql.conf中配置参数shared_preload_libr......
  • [Dubbo] Dubbo 反序列化将Pair转化成HashMap的问题
    问题描述Dubbo在3.2.x版本中,类检查级别默认是STRICT3.1版本中默认为WARN告警级别,3.2版本中默认为STRICT严格检查级别。不配置的情况下,会将名单以外的类型转化成Map。如何支持Pair的序列化和反序列化dubbo.application.serialize-check-status=WARN新建允许的名......
  • 基于springboot的高校招生系统(含源码+sql+视频导入教程+文档+PPT)
    ......
  • java毕设安卓基于Android的志愿者服务系统(开题+源码)
    本系统(程序+源码)带文档lw万字以上 文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容一、研究背景在当今信息化社会,移动互联网技术的迅猛发展正深刻改变着人们的生活方式。特别是在社会公益领域,志愿者服务作为社会文明进步的重要标志,其组织与管......
  • 学生考勤系统|基于Springboot的大学生考勤系统设计与实现(源码+数据库+文档)
    大学生考勤系统目录目录基于Springboot的大学生考勤系统设计与实现一、前言二、系统功能设计三、系统实现1、系统登录注册2、管理员功能模块四、数据库设计1、实体ER图 2、具体的表设计如下所示:五、核心代码 六、论文参考 七、最新计算机毕设选题推荐八、源码......
  • 基于java+springboot+vue实现的物业管理系统(文末源码+Lw+ppt)23-23
    摘  要快速发展的社会中,人们的生活水平都在提高,生活节奏也在逐渐加快。为了节省时间和提高工作效率,越来越多的人选择利用互联网进行线上打理各种事务,通过线上物业管理系统也就相继涌现。与此同时,人们开始接受方便的生活方式。他们不仅希望页面简单大方,还希望操作方便,可以快......
  • 基于java+springboot+vue实现的停车场管理系统(文末源码+Lw)23-258
    摘 要如今社会上各行各业,都喜欢用自己行业的专属软件工作,互联网发展到这个时候,人们已经发现离不开了互联网。新技术的产生,往往能解决一些老技术的弊端问题。因为传统停车场管理系统信息管理难度大,容错率低,管理人员处理数据费工费时,所以专门为解决这个难题开发了一个停车场管......
  • 基于java+springboot+vue实现的停车场管理系统(文末源码+Lw)23-258
    摘 要如今社会上各行各业,都喜欢用自己行业的专属软件工作,互联网发展到这个时候,人们已经发现离不开了互联网。新技术的产生,往往能解决一些老技术的弊端问题。因为传统停车场管理系统信息管理难度大,容错率低,管理人员处理数据费工费时,所以专门为解决这个难题开发了一个停车场管......