zoukankan      html  css  js  c++  java
  • HashMap

    图1

    HashMap 底层就是一个数组结构,数组中的每一项又是一个链表。当新建一个 HashMap 的时候,就会初始化一个数组。

    //源码=============================

    public V put(K key, V value) {  
        // 处理key为null,HashMap允许key和value为null  
        if (key == null)  
            return putForNullKey(value);  
        // 得到key的哈希码  
        int hash = hash(key);  
        // 通过哈希码计算出bucketIndex  
        int i = indexFor(hash, table.length);  
        // 取出bucketIndex位置上的元素,并循环单链表,判断key是否已存在  
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {  
            Object k;  
            // 哈希码相同并且对象相同时  
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {  
                // 新值替换旧值,并返回旧值  
                V oldValue = e.value;  
                e.value = value;  
                e.recordAccess(this);  
                return oldValue;  
            }  
        }  
      
        // key不存在时,加入新元素  
        modCount++;  
        addEntry(hash, key, value, i);  
        return null;  
    }  


     void addEntry(int hash, K key, V value, int bucketIndex) {

            if ((size >= threshold) && (null != table[bucketIndex])) {

                resize(2 * table.length);

                hash = (null != key) ? hash(key) : 0;

                bucketIndex = indexFor(hash, table.length);

            }

     //==============

           createEntry(hash, key, value, bucketIndex);

        }

     void createEntry(int hash, K key, V value, int bucketIndex) {

            Entry<K,V> e = table[bucketIndex];

            table[bucketIndex] = new Entry<>(hash, key, value, e);

            size++;

        }

     Entry(int h, K k, V v, Entry<K,V> n) {

                value = v;

                next = n;

                key = k;

                hash = h;

            }

  • 相关阅读:
    Codeforces 1485C Floor and Mod (枚举)
    CodeForces 1195D Submarine in the Rybinsk Sea (算贡献)
    CodeForces 1195C Basketball Exercise (线性DP)
    2021年初寒假训练第24场 B. 庆功会(搜索)
    任务分配(dp)
    开发工具的异常现象
    Telink MESH SDK 如何使用PWM
    Telink BLE MESH PWM波的小结
    [LeetCode] 1586. Binary Search Tree Iterator II
    [LeetCode] 1288. Remove Covered Intervals
  • 原文地址:https://www.cnblogs.com/duanR/p/8057954.html
Copyright © 2011-2022 走看看