当前位置:网站首页>Rewrite equals why rewrite hashcode
Rewrite equals why rewrite hashcode
2022-07-18 22:02:00 【Luoluo 1024】
rewrite equals Why rewrite hashcode?
Premise
Let's get to know object class
public class Object {
// Compare memory addresses for equality
public boolean equals(Object obj) {
return (this == obj);
}
// Convert the internal address of the object into an integer , That is to say hash value
public native int hashCode();
//........ Omitted code .............
}
example
Suppose in business , We think that the same name is the same person
public class Student {
private String name;
private Integer age;
// .... Omit getter and setter Method ....
@Override
public boolean equals(Object o) {
// We think that the same name is the same person
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(name, student.name);
}
}
guess
If you do not override hashcode What's going to happen
public static void main(String[] args) {
Map<Object, Object> map = new HashMap<>(4);
Student student1 = new Student("zhangsan", 11);
Student student2 = new Student("zhangsan", 22);
map.put(student1,student1);
map.put(student2,student2);
System.out.println(map.size());
}
Let's see below. map Of put What happened to the operation ?
//hashmap Of hash Algorithm
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
Node<K,V>[] tab; Node<K,V> 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<K,V> e; K k;
//1、 Compare first key Of hash Whether the values are equal , Compare again key Whether the memory addresses of are equal perhaps key Of equals Whether it is equal or not
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//2、hash It's not equal , Compare it again TreeNode type
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//3、 Whether there are equal nodes in the linked list
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
// The next node of the current linked list is empty
p.next = newNode(hash, key, value, null);// Add a new node
if (binCount >= TREEIFY_THRESHOLD - 1) // The length of the list is greater than or equal to 7 , The tree, , Exit loop
treeifyBin(tab, hash);
break;
}
// Whether the next node is equal to the nodes to be added , It's the exit loop
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
// Continue to walk behind the linked list
p = e;
}
}
// If the same node exists in the linked list , Return old value
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;
}
We find that when there is conflict , The order of judgment is as follows
- Compare first key Of hash Whether the values are equal , Compare again key Whether the memory addresses of are equal perhaps key Of equals Whether it is equal or not
- hash It's not equal , Compare it again TreeNode type
- Whether there are equal nodes in the linked list
Because we think that the same name is the same person
When put When , Compare first student1 and student2 Of hash value , because student1 and student2 It's a different object , their hashcode Method is called object.hashcode Method , It compares the address of the object , Obviously , It is calculated by the following method hash It's not equal
//hashmap Of hash Algorithm
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
hash Value inequality , Neither TreeNode type , Add to linked list
There's a contradiction
But now the name is the same , But in map But there are two people , It's obviously against our original intention
Obviously , The reason for the contradiction is to call object.hashcode Method , Calculate the unequal hash value , If hash The values are equal , Can meet the following if sentence
//1、 Compare first key Of hash Whether the values are equal , Compare again key Whether the memory addresses of are equal perhaps key Of equals Whether it is equal or not
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
e = p;
So , I want to design something with the same name student Produce the same hash value
rewrite hashcode
We know that different values may produce the same hash value , But in map This problem does not exist , Because when hash When the values are equal , And compare it equals Method , But we should also try to avoid hash Collision , After all hash Collision still has a little impact on performance
@Override
public int hashCode() {
return Objects.hash(name);
}
Sum up , rewrite equals To rewrite hashcode Just to avoid being like map In such a data structure , Prohibit the same key There are multiple value value .
end !!!
边栏推荐
- A risk assessment method of physical information leakage in classified places
- Research on Intelligent Monitoring Technology in cyberspace defense
- 阿里云、华为云、谷歌云都已入局,盘点13家云计算厂商的RPA
- Win11老是弹出输入体验怎么办
- Leetcode day 23
- Low code development builds business process management solutions
- MySQL trigger
- 十大OA系统排行
- Leetcode 1309. 解码字母到整数映射(可以,一次过)
- Leetcode 1332. 删除回文子序列(看完题解才恍然大悟!!!!!!!)
猜你喜欢
随机推荐
Leetcode day 23
LETV has become the king of anti involution: employees have lived a fairy life without 996!
CONDA installation requirements Txt specified dependent package
Neutral energy optimization of transport layer triple handshake
Application of Apache E8 industrial computer minipicecan card in Construction Robot
Inventory of major RPA products at home and abroad
低代码平台搭建学生事务一门式管理系统解决方案
Research on Intelligent Monitoring Technology in cyberspace defense
localStorage、sessionStorage存储字符串或数字注意点
MySQL index
Eight mainstream OA office software competition, traditional vs. rookie, who do you pick?
阿普奇 E8 工控机——MinipiceCAN卡在建筑机器人的应用
深入剖析多重背包问题(下篇)
App packet capturing tips how to break network exceptions?
One person builds the digital system solution of the whole group with a low code development platform
降噪蓝牙耳机哪款好?性价比最高的主动降噪蓝牙耳机
Characteristics and usage of Ni MH battery (FDK Ni MH battery charging mechanism)
Application of Apache abox-700 industrial computer minipicecan card in electric power inspection robot
6G synaesthesia integrated networking integration technology
栓Q了,大厂被强制毕业,空窗一个月死背八股文,还好拿到了Offer









