[英]How does get method works in hashmap if hashcode returns a contant value and equals return false?
I have Dept class as follows, i have overridden hashcode and equals method.我有如下 Dept 类,我覆盖了 hashcode 和 equals 方法。 Hashcode returns a constant value and equals return false always. Hashcode 返回一个常量值,并且 equals 总是返回 false。
public class Dept {
private int depid;
private String deptname;
public Dept(int depid, String deptname) {
super();
this.depid = depid;
this.deptname = deptname;
}
public int getDepid() {
return depid;
}
public void setDepid(int depid) {
this.depid = depid;
}
public String getDeptname() {
return deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
@Override
public int hashCode() {
return 100;
}
@Override
public boolean equals(Object obj) {
return false;
}
@Override
public String toString() {
return "Dept [depid=" + depid + ", deptname=" + deptname + "]";
}
}
I have a main method我有一个主要的方法
public static void main(String[] args) {
Dept dept = new Dept(1, "it");
Dept dept1 = new Dept(1, "it");
Dept dept2 = new Dept(1, "it");
HashMap<Dept, String> map = new HashMap<>();
map.put(dept, "a");
map.put(dept1, "b");
map.put(dept2, "c");
System.out.println(map.get(dept2));// returns c
System.out.println(map.get(dept1));// returns b
}
According to the theory i have read, hashcode returning a constant value will give us the same index of bucket in hashmap hence values are stored in a single bucket For equals method, it is returning false and hence logically same dept object are saved multiple times.根据我读过的理论,返回一个常量值的哈希码会给我们哈希图中相同的桶索引,因此值存储在单个桶中 对于 equals 方法,它返回 false,因此逻辑上相同的 dept 对象被保存多次。 How is get method returning the exact correct value from hashmap? get 方法如何从 hashmap 返回准确正确的值?
由于一个对象总是应该equals
它自己, HashMap
首先使用==
(object identity) 检查,因为这要快得多,并且会在许多常见用例中匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.