HashMap详细介绍

0、基于jdk1.8源码所分析

1、一些常量

  /**
     * The default initial capacity - MUST be a power of two.          默认的初始容量是2的幂。 默认为2的4次方 16
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16  

    /**
     * The maximum capacity, used if a higher value is implicitly specified        最大容量。 2的30次方
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.   负载因子
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

2、什么是初始化容量以及负载因子

初始化容量默认16.就是map里面能存16个键值队。
负载因子0.75 即: 一旦存放元素个数 >=  0.75*16 -1 = 11 就会进行扩容 

3、那么负载因子为什么要是0.75 源码注释这么写

Ideally, under random hashCodes, the frequency of
* nodes in bins follows a Poisson distribution
* (http://en.wikipedia.org/wiki/Poisson_distribution) with a
* parameter of about 0.5 on average for the default resizing
* threshold of 0.75, although with a large variance because of
* resizing granularity. Ignoring variance, the expected
* occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
* factorial(k)). The first values are:
*
* 0: 0.60653066
* 1: 0.30326533
* 2: 0.07581633
* 3: 0.01263606
* 4: 0.00157952
* 5: 0.00015795
* 6: 0.00001316
* 7: 0.00000094
* 8: 0.00000006
*
在理想情况下,使用随机哈希码,节点出现的频率在hash桶中遵循泊松分布,同时给出了桶中元素个数和概率的对照表。

从上面的表中可以看到当桶中元素到达8个的时候,概率已经变得非常小,也就是说用0.75作为加载因子,每个碰撞位置的链表长度超过8个是几乎不可能的。
所以用0.75.

1、构造方法

// 默认构造函数。
HashMap()

// 指定“容量大小”的构造函数
HashMap(int capacity)

// 指定“容量大小”和“加载因子”的构造函数
HashMap(int capacity, float loadFactor)

// 包含“子Map”的构造函数
HashMap(Map<? extends K, ? extends V> map)


2、方法


void                 clear()   清空容器中元素
Object               clone() 克隆
boolean              containsKey(Object key)  判断是否包含key
boolean              containsValue(Object value)   是否包含value
Set<Entry<K, V>>     entrySet()              所有的key的集合
V                    get(Object key)             
boolean              isEmpty()
Set<K>               keySet()
V                    put(K key, V value)
void                 putAll(Map<? extends K, ? extends V> map)
V                    remove(Object key)
int                  size()           map容器中元素个数
Collection<V>        values()

3、存储的方式

1、hashmap底层是以数组方式进行存储。将key-value对作为数组中的一个元素进行存储。
2、key-value都是Map.Entry中的属性。其中将key的值进行hash之后进行存储,即每一个key都是计算hash值,然后再存储。一个Hash值对应一个数组下标,数组下标是根据hash值和数组长度计算得来。
3、由于不同的key有可能hash值相同,即该位置的数组中的元素出现两个,对于这种情况,hashmap采用链表形式进行存储。

//存储kev -value键值队
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash; //hash值
        final K key;	 //key
        V value;    // value值
        Node<K,V> next;  // 链表引用. 防止出现key不同,hash相同

		//构造函数,生成节点
        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }  
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }
  
    // 重写hashcode方法
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }
		
		//同一个key时,新值替换旧值,返回旧的值
        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }
		
		//重写equals方法
        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

4、put方法


	public V put(K key, V value) {
		//hash(key) 生成hashCode   
        return putVal(hash(key), key, value, false, true);
    }
	//用来生成hashCode
	tatic final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
	
/**
     * Implements Map.put and related methods
     * @param hash hash for key   hash值
     * @param key the key         key
     * @param value the value to put      value
     * @param onlyIfAbsent if true, don't change existing value  如果为true则不能更改
     * @param evict if false, the table is in creation mode.        如果为false则表为创建模式
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
         //tab为数组的大小,p表示tab上的某个节点,n为tab的长度,i为tab的下表
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //首次存储,初始化空间(tab==null)
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //(n-1)&hash得到下标i。有时间我会讲解如何算出来的。将tab[i]赋值给p.若当前p==null,则当前下标没有节点,直接赋值
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {//说明当前数组的该下标有值,开始链表的方式。
            Node<K,V> e; K k;   //定义e表示即将插入的节点。  定义K
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))  //判断原来的链表中有没有key值相等的,相等就从新赋值就结束了
                e = p;
            else if (p instanceof TreeNode)//说明hash相等,但是key不相等。就往红黑树放。判断有没有生成红黑树节点个大于8?
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }


待更新

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SpringCloud1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值