我已经在Internet上看到了2个版本的过程,因为发生碰撞时会发生什么。
版本1(最看见的一个):
当数组的特定位置已经存在一个元素时,请调用equals()检查它们是否相同:如果是,则拒绝插入。如果不是,请插入新元素。
版本2:
当已经存在一个特定位置的元素时
数组,Indoke HashCode()方法以比较其哈希码。如果他们
哈希码不同,插入新元素。如果它们是一样的,
然后调用equals(),并执行与第一个版本相同的。
我想知道哪一个在Java8中是正确的。
I have seen 2 versions of the procedure on the internet for what happens when there is a collision.
Version 1 (the most seen one):
When there IS an element already at that specific position of the array, invoke equals() to check if they are the same: If yes, insertion denied. If not, insert the new element.
Version 2 :
When there IS an element already at that specific position of the
array, invoke hashCode() method to compare their hashCode. If their
hashCode is different,insert the new element. If they are the same,
then invoke equals() and do the same as the first version.
I wonder which one is correct in Java8.
发布评论
评论(1)
我们可以检查JDK源代码以回答此问题。查看实现我们可以看到,它基本上是哈希图上的包装器,使用地图的密钥来实现集合。
搬到实施,我们可以看到 都检查了哈希码和平等,但是哈希码首先发生,如果true,则会将评估短路。
在地图由红黑树支持的情况下,也会发生类似的事情(请参阅
puttreeval
方法的实现)。We can inspect the JDK source code to answer this question. Looking at the HashSet implementation we can see that it is basically a wrapper over HashMap, using the Map's keyset to implement the Set.
Moving to the HashMap implementation, we can see that both hashcode and equals are checked, however hashcode happens first and will short circuit the evaluation if true.
A similar thing happens in the case of the Map being backed by a red-black tree (see the
putTreeVal
method's implementation).