哈希表 get() 操作无法按照文档进行操作

Hashtable get() operation not working as per documentation

根据 Java 哈希表 class (https://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html) 的官方文档,get() 操作将 return 它的记录值之一,如果说value 有一个键,当参数被输入到该键的 equals() 操作中时,该键 return 为真。

因此,理论上,对于 Hashtable 的两个 get() 查询,以下代码应该 return "Hello!":

public static class Coordinates implements Serializable {

    private int ex;
    private int why;

    public Coordinates(int xCo, int yCo) {
        ex = xCo;
        why = yCo;
    }

    public final int x() {
        return ex;
    }

    public final int y() {
        return why;
    }

    public boolean equals(Object o) {
        if(o == null) {
            return false;
        } else if(o instanceof Coordinates) {
            Coordinates c = (Coordinates) o;
            return this.x() == c.x() && this.y() == c.y();
        } else {
            return false;
        }
    }
}

Hashtable<Coordinates, String> testTable = new Hashtable<Coordinates, String>();
Coordinates testKey = new Coordinates(3, 1);
testTable.put(testKey, "Hello!");
testTable.get(testKey); //This will return the "Hello" String as expected.
testTable.get(new Coordinates(3, 1)); //This will only return a null value.

但是,get() 无法正常工作。它似乎只有在你随意地向它提供与原始密钥完全相同的对象时才有效。

是否有任何方法可以更正此问题并使哈希表按照文档中描述的方式运行?我是否需要对坐标 class 中的自定义 equals() 操作进行任何调整?

为了能够从基于散列的集合中存储和检索对象,您应该 implement/oeverride equals() 以及 Object [=27] 的 hashCode() 方法=].在您的情况下,您已经覆盖 equals() 并将 hashCode() 方法保留为从 Object.

继承的默认实现

Here is the general contracthashCode() 方法在实施时必须考虑:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

这是从我的 IDE 生成的示例实现(@Peter 在评论区已经提到),您可以修改它以满足您的要求:

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ex;
    result = prime * result + why;
    return result;
}