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;

            }

  • 相关阅读:
    iOS的几种动画使用
    iOS工程师必备技能
    网络数据的下载(NSUrlconnection异步下载和NSstring同步下载)和UI界面数据的刷新(都是抛弃第三方库的一些本质)
    GCD定时器
    iOS开发的小技巧
    站在巨人的肩膀上
    跳转系统设置相关界面的方法
    微信分享
    网站 、内容
    加水印
  • 原文地址:https://www.cnblogs.com/duanR/p/8057954.html
Copyright © 2011-2022 走看看