Mer*_*tce -1 java equals hashmap hashcode
我想我做了所有事情,但HashMap.get返回null.hashCode返回相同的整数,equals返回true,key是不可变的,但现在仍在工作.
我错过了什么?
这是我的代码:
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);
...
Run Code Online (Sandbox Code Playgroud)
打印结果如下:
hashCode:true equals:true Map Size:1 other_objjj:null
任何人都能看到我失踪的东西吗?
你还没有覆盖这个equals(Object)方法; 你重载了它equals(MyClass).
像这样做:
@Override
public final boolean equals(Object obj2)
{
if (obj2 == this) return true;
if (!(obj2 instanceof MyClass)) return false;
MyClass that = (MyClass) obj2;
return (enum1.equals(that.getEnum1()) && enum2.equals(that.getEnum2()));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1385 次 |
| 最近记录: |