When two objects have same value of ele
in class A then those two objects are equal. So I have overridden toString and hashCode to return the object's ele
(not considering the value of s
anywhere).
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)
.
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. A map will use equals
to the final ruler on equality after it uses the hash code. 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
. Then you will see that val2
will be returned for both get
calls.
You need to implement equals() to take ele
value into consideration when adding to a map, ie:
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. So, a1
and a2
both are different Object in actual.
Please Refer this for more info about new
keyword What New keyword do Internally in Java
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.