HashMap

一继承关系

  • 实现父类抽象方法put,entrySet,重写父类增删改查方法


    image.png

二.结构

默认容量
 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
扩容因子
 static final float DEFAULT_LOAD_FACTOR = 0.75f;
  • 存储结构 Entry<K,V>数组加链表
  static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;//包含下一个指向的引用
        int hash;
     ....
    }
  • put与get方法
  public V put(K key, V value) {
        int hash = hash(key);
        int i = indexFor(hash, table.length);
        //如果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不同则增加Entry数组
        addEntry(hash, key, value, i);
        return null;
    }

void addEntry(int hash, K key, V value, int bucketIndex) {
        if ((size >= threshold) && (null != table[bucketIndex])) {
            //当数组容量>大于数组大小的0.75时(默认情况),扩容两倍
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }
        createEntry(hash, key, value, bucketIndex);
    }

//根据 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);//构造 Entry并加到 Entry数组中
        size++;
    }
//遍历指定index的数组及next元素
   for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
image.png
  • hashcode如何取值
  final int hash(Object k) {
        int h = hashSeed;
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }
        h ^= k.hashCode();//调用native方法
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

三.三种视图

  • entrySet(): 返回此映射所包含的映射关系的 Set 视图。
  • keySet():返回此映射中所包含的键的 Set 视图。
  • values():返回此映射所包含的值的 Collection 视图。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,997评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,745评论 18 399
  • java笔记第一天 == 和 equals ==比较的比较的是两个变量的值是否相等,对于引用型变量表示的是两个变量...
    jmychou阅读 5,427评论 0 3
  • 前言 前面四篇说了线性表和链表,并且也手写了其中一些的实现原理,我们先说说他们的数据结构数组:它采用了连续的内存存...
    小窦子阅读 3,652评论 0 3
  • Docker安装 以Ubuntu为例:https://yeasy.gitbooks.io/docker_pract...
    韬韬不绝阅读 2,773评论 0 0

友情链接更多精彩内容