• 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;

            }

  • 相关阅读:
    C++头文件,预处理详解
    在VS2013中查看C/C++预处理后的文件
    使用apache.lang包安全简洁地操作Java时间
    FileInputStream 和 FileOutputStream
    【转】彻底搞清计算结构体大小和数据对齐原则
    NDK学习笔记-gdb调试
    NDK学习笔记-gdb调试
    NDK学习笔记-多线程与生产消费模式
    NDK学习笔记-多线程与生产消费模式
    Android-Makefile
  • 原文地址:https://www.cnblogs.com/duanR/p/8057954.html
Copyright © 2020-2023  润新知