I think I did every thing but HashMap.get returns null.
hashCode returns same integer, equals returns true, key is immutable, but still now working.
What am I missing?
Here is my code:
public enum MyEnum_1 `AA1, AA2, AA3, AA4`;
public enum MyEnum_2 `BB1, BB2, BB3, BB4`;
public void MyClass()
{
...
final MyEnum_1 enum1;
final MyEnum_2 enum2;
public int hashCode()
{
return (enum1.ordinal() * 100 + enum2.ordinal());
}
public boolean equals(MyClass obj2)
{
if (obj2 == null) return false;
else return (enum1.equals(obj2.getEnum1()) && enum2.equals(obj2.getEnum2()));
}
...
}
...
Map<MyClass, MyOtherClass> mappp = new HashMap<MyClass, MyOtherClass>();
...
mappp.put(obj1, other_obj1);
MyClass obj2 = new MyClass(obj1.getEnum1(), obj1.getEnum2());
System.out.println("hashCode: " + (obj1.hashCode() == obj2.hashCode()));
System.out.println("equals: " + obj1.equals(obj2));
System.out.println("Map Size: " + mappp.size());
MyOtherClass other_objjj = mappp.get(obj2);
System.out.println("other_objjj: " + other_objjj);
...
Print RESULTS are as follows:
hashCode: true
equals: true
Map Size: 1
other_objjj: null
Can any one see what I am missing, please?
You haven’t overridden the
equals(Object)method; you overloaded it withequals(MyClass).Do it like this: