[英]Java - Overriding hashCode and toString
When two objects have same value of ele
in class A then those two objects are equal. 当两个对象在A类中具有相同的
ele
值时,则这两个对象相等。 So I have overridden toString and hashCode to return the object's ele
(not considering the value of s
anywhere). 因此,我重写了toString和hashCode以返回对象的
ele
(不考虑s
的值)。
public class A {
private int ele;
private String s;
public int getEle() {
return ele;
}
public void setEle(int ele) {
this.ele = ele;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
@Override
public int hashCode(){
return ele;
}
@Override
public String toString() {
return String.valueOf(ele);
}
}
public static void main(String[] args) {
Map<A, String> map = new HashMap<>();
A a1 = new A();
a1.setEle(10);
a1.setS("abc");
A a2 = new A();
a2.setEle(10);
a2.setS("efg");
map.put(a1, "val1");
map.put(a2, "val2");
System.out.println(map.get(a1));
System.out.println(map.get(a2));
}
Output: 输出:
val1
val2
But if I put value of a1
and a2
in a map, I was expecting either val1
or val2
to be returned for both map.get(a1)
and map.get(a2)
. 但是,如果我将
a1
和a2
值放在地图中,则我希望为map.get(a1)
和map.get(a2)
都返回val1
或val2
。
Sure, a1
and a2
have the same hash code, but they weren't considered equal because you didn't override equals
to consider two A
objects with the same ele
to be equal. 当然,
a1
和a2
具有相同的哈希码,但是它们没有被视为相等,因为您没有重写equals
就将具有相同ele
两个A
对象视为相等。 A map will use equals
to the final ruler on equality after it uses the hash code. 使用哈希码后,地图将使用
equals
最终平等的最终标尺。 The map will place both objects in the same bucket, but because they aren't equal, it will keep both. 该地图会将两个对象都放在同一个存储桶中,但是由于它们不相等,因此将两者都保留。
Override equals
so that it returns true
if the other object is an A
and they both have the same ele
. 覆盖
equals
因此如果另一个对象是A
并且它们都具有相同的ele
,则它返回true
。 Then you will see that val2
will be returned for both get
calls. 然后,您将看到两个
get
调用都将返回val2
。
You need to implement equals() to take ele
value into consideration when adding to a map, ie: 添加到地图时,需要实现equals()以将
ele
值考虑在内,即:
public class A {
private int ele;
private String s;
public int getEle() {
return ele;
}
public void setEle(int ele) {
this.ele = ele;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
A a = (A) o;
return ele == a.ele;
}
@Override
public int hashCode() {
return ele;
}
}
This will make you return only one value as you want. 这将使您仅返回所需的一个值。
every time you use new
keyword it makes a new object
in heap
Memory. 每次使用
new
关键字都会在heap
内存中创建一个新object
。 So, a1
and a2
both are different Object in actual. 因此,
a1
和a2
在实际中都是不同的对象。
Please Refer this for more info about new
keyword What New keyword do Internally in Java 请参考此以获得有关
new
关键字的更多信息What What关键字在Java内部进行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.