-1

我想我做了所有事情,但 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);
...

打印结果如下:

hashCode: true 等于: true 地图大小: 1 other_objjj: null

任何人都可以看到我错过了什么吗?

4

1 回答 1

8

您还没有覆盖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()));
}
于 2013-02-06T00:55:13.680 回答