Hashmap源码分析

写在前面

本文是针对JDK版本1.8的,可能与其他版本有出入。

全局变量

// 序列化id
private static final long serialVersionUID = 362498820763181265L;

// 默认容量16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

// 最大容量 2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30;

// 默认负载因子 0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;

// 当桶结点大于8时,当前链表会转换成红黑树
static final int TREEIFY_THRESHOLD = 8;

// 当桶结点小于6时,当前红黑树会转换成链表 
static final int UNTREEIFY_THRESHOLD = 6;

//转红黑树时, table的最小长度 
static final int MIN_TREEIFY_CAPACITY = 64;

// 存储元素的数组,transient关键字表示该属性不能被序列化
transient Node<K,V>[] table;

// 将数据转换成set的另一种存储形式,这个变量主要用于迭代功能
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;  // 下一个结点
        }
     
     	......
}

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

		......
}

构造方法

hashmap一共有4个构造方法,如下

// 传入参数为初始容量和负载因子
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;
        this.threshold = tableSizeFor(initialCapacity);
    }


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



public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}


public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}

重点

未完

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值