android 获取元素的下标_Java-Android-HashMap(Jdk1.8)较深入剖析-源码篇-容量下标的巧妙处理...

这篇主要也是大体上进行代码的流程以及一些处理逻辑做简单的分析,红黑树部分还不太懂(没怎么刷过算法和理过思路,后面应该还是要补上算法的部分):

构造函数:

HashMap

/**

* Constructs an empty HashMap with the specified initial

* capacity and load factor.

*

* @param initialCapacity the initial capacity

* @param loadFactor the load factor

* @throws IllegalArgumentException if the initial capacity is negative

* or the load factor is nonpositive

*/

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);

}

/**

* Constructs an empty HashMap with the specified initial

* capacity and the default load factor (0.75).

*

* @param initialCapacity the initial capacity.

* @throws IllegalArgumentException if the initial capacity is negative.

*/

public HashMap(int initialCapacity) {

this(initialCapacity, DEFAULT_LOAD_FACTOR);

}

/**

* Constructs an empty HashMap with the default initial capacity

* (16) and the default load factor (0.75).

*/

public HashMap() {

this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted

}

/**

* Constructs a new HashMap with the same mappings as the

* specified Map. The HashMap is created with

* default load factor (0.75) and an initial capacity sufficient to

* hold the mappings in the specified Map.

*

* @param m the map whose mappings are to be placed in this map

* @throws NullPointerException if the specified map is null

*/

public HashMap(Map extends K, ? extends V> m) {

this.loadFactor = DEFAULT_LOAD_FACTOR;

putMapEntries(m, false);

}

主要是两点:初始容量+装载因子

this.loadFactor = loadFactor;

this.threshold = tableSizeFor(initialCapacity);

而当我们创建的时候如果传入初始容量,将会进行2的n次方的矫正,具体看tableSizeFor函数:

/**

* Returns a power of two size for the given target capacity.

*/

static final int tableSizeFor(int cap) {

int n = cap - 1;

n |= n >>> 1; ///< 现将n无符号右移1位,并将结果与右移前的n做按位或操作,结果赋给n;

n |= n >>> 2;

n |= n >>> 4;

n |= n >>> 8;

n |= n >>> 16;

///< 中间过程的目的就是使n的二进制数的低位全部变为1

return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;

}

一开始可能会有为难情绪,有点蒙....小白就慢慢来推导呗!(我们学习hash的源码,主要是要了解人家的设计思想,了解hash的特性,同时还能再学点人家的代码规范啥的,有助于我们更好的使用它,同时提升我们对于较难问题的理解能力).

其他的数字均可以推导看看

也就是说该算法的目的就是返回一个比传入的容量大且为2的n次幂的一个数。确实巧妙...算法的本身就是把第一个1后面不停的变为1(精髓...)。

put函数 - 直接整put算了....

/**

* Associates the specified value with the specified key in this map.

* If the map previously contained a mapping for the key, the old

* value is replaced.

*

* @param key key with which the specified value is to be associated

* @param value value to be associated with the specified key

* @return the previous value associated with key, or

* null if there was no mapping for key.

* (A null return can also indicate that the map

* previously associated null with key.)

*/

public V put(K key, V value) {

return putVal(hash(key), key, value, false, true);

}

--hash(key)了解一下

/**

* Computes key.hashCode() and spreads (XORs) higher bits of hash

* to lower. Because the table uses power-of-two masking, sets of

* hashes that vary only in bits above the current mask will

* always collide. (Among known examples are sets of Float keys

* holding consecutive whole numbers in small tables.) So we

* apply a transform that spreads the impact of higher bits

* downward. There is a tradeoff between speed, utility, and

* quality of bit-spreading. Because many common sets of hashes

* are already reasonably distributed (so don't benefit from

* spreading), and because we use trees to handle large sets of

* collisions in bins, we just XOR some shifted bits in the

* cheapest possible way to reduce systematic lossage, as well as

* to incorporate impact of the highest bits that would otherwise

* never be used in index calculations because of table bounds.

*/

static final int hash(Object key) {

int h;

return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);

}

--最终hash值 = 低16位与高16位异或的值- 右移16位保证了高十六位与任何数异或都是本身

hashmap中要找到某个元素,需要根据key的hash值来求得对应数组中的位置.

key的hash值高16位不变,低16位与高16位异或作为key的最终hash值。

(h >>> 16,表示无符号右移16位,高位补0,任何数跟0异或都是其本身,因此key的hash值高16位不变。)

哇!小白又了解了一些个知识。。。

--putVal(关键函数) - 先走下逻辑

/**

* Implements Map.put and related methods

*

* @param hash hash for key

* @param key the key

* @param value the value to put

* @param onlyIfAbsent if true, don't change existing value

* @param evict if false, the table is in creation mode.

* @return previous value, or null if none

*/

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,

boolean evict) {

Node[] tab; Node p; int n, i;

if ((tab = table) == null || (n = tab.length) == 0)

n = (tab = resize()).length;

if ((p = tab[i = (n - 1) & hash]) == null)

tab[i] = newNode(hash, key, value, null);

else {

Node e; K k;

if (p.hash == hash &&

((k = p.key) == key || (key != null && key.equals(k))))

e = p;

else if (p instanceof TreeNode)

e = ((TreeNode)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;

}

hash值我们有了。然后我们看如何往tab数组中插入值...

1.首先如果transient Node[] table;数组是空或者大小为0,则重新分配空间

resize成了关键了..

先看一段为空分配的情况:

有些逻辑不用看,不是为空的逻辑。所以基本上分配大小就是

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

所以默认情况下我们创建HashMap的时候容量就是16.这个习惯不是太好,如果相对还是知道大概需要的容量的话,尽量传入容量参数!以为如果发现容量不够进行多次扩容的话,是对性能有所损耗,而且对于多线程的安全性又增加了一定的风险?怎么说,你看resize后面的代码:

1.2 扩容之后会将原来的数据转移到新的容器当中,同时原来的容器置空

其中JDK1.8还涉及到了红黑色的结构(针对性能做了提升).具体红黑色不太懂了(后面专门研究下算法吧)。

1.3 而如果再已有的数组进行扩容,将是原来的2倍

从代码也可以看出来。很多时候面试可能会被问到。 当然为什么一定要是原来的2倍?

2. 我们看下找位置这个地方:

更精髓的是,我们的容量整好是2的n次幂除了索引在范围内,更重要的是将hash冲突最小化。怎么说:如果你length - 1中某一位为0,对应的h的某一位结果都会是0,这样就很大成都上导致两个h取得相同的hash值,导致hash冲突。而我们的length是2的n次幂,再减去1,获得二进制位数全部都是1,这样就减少了冲突!

这样如果面试考官问到,我们可以告诉它HashMap的下标是如何定位的。采用了什么巧妙的算法。

3.然后看下存放的大体逻辑

3.1 找到的位置上没有直接存放

找到的位置上已经存在某个节点

3.2 但是hash相同,key相同(对象或者内容)

3.3 如果是TreeNode类型的节点

3.4 创建一个新的节点存储

3.5 最后还进行了调整 - afterNodeAccess ///< 将最近使用的Node,放在链表的最末尾

如果空间不够了,还会进行扩容处理

就是之前的resize函数....

大体上就是这样的一个流程,前面一些个相关的巧妙的处理,其实如果要真正明白为什么,应该还会比较难。小白目前也只是知道,这样设计的好处,简单了解这样设计的原因,至于人家为什么要这样搞。每个扎实的算法功底和熟练度,怕是老火,反正自己感觉是老火。

到目前为止也只是多了解了一些,小白后续还想看下这个节点的存储,以及1.8涉及到的红黑色的部分,这个应该是比较难的点吧,to me。

最后总结下:通过以上了解,可以大概知道容量分配,2的n次幂,hash冲突,巧妙的计算的地方,hash的基本原理,差不多也能了解比一般要深一些。

后面还得继续深入看下具体存储算法....头都大了,哎!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值