首页 > 其他 > 详细

HashMap重点源码剖析

时间:2019-08-23 21:23:50      阅读:90      评论:0      收藏:0      [点我收藏+]

HashMap源码阅读:

1,概述

2,HashMap核心成员变量

3,HashMap构造函数

4,HashMap核心方法

 

1,概述

搞java的人,都应该知道hashMap的底层数据结构是一个数组+链表(+红黑树)。

大体思路:首先是基于key做hash操作,然后与数组长度取模,定位到某个数组位置。如果冲突了(可能是hash冲突,或者是hash值与长度取模之后),就会在该数组位置再挂一个链表。jdk1.8以后当链表长度达到8之后,就转化为红黑树(因为链表的时间复杂度是N,红黑树是log N),提升了性能。

以上是大概思路,其实jdk源码是优化的,比如hash算法,取模操作这些都是位运算来替代的,等到后面看源码的时候再来好好撸撸。

 

2,HashMap核心成员变量

先看看HashMap的核心成员:


static
final int DEFAULT_INITIAL_CAPACITY = 1 << 4; static final int MAXIMUM_CAPACITY = 1 << 30; static final float DEFAULT_LOAD_FACTOR = 0.75f; static final int TREEIFY_THRESHOLD = 8; static final int UNTREEIFY_THRESHOLD = 6; static final int MIN_TREEIFY_CAPACITY = 64; transient Node<K,V>[] table; static class Node<K,V> implements Map.Entry<K,V> { final int 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; } public final K getKey() { return key; } public final V getValue() { return value; } public final String toString() { return key + "=" + value; } public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } 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; } }

 

HashMap重点源码剖析

原文:https://www.cnblogs.com/xtz2018/p/11402605.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!