小编典典
为了在上面详细说明我的评论,您的Point类应该实现哈希码,并且应如下所示:(存在许多实现,这只是一个可行的实现)假设实例的变量为x和y。
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
if (x != point.x) return false;
if (y != point.y) return false;
return true;
}
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
否则,如果您不重写这些方法,则ObjectJavadoc可以很好地说明您的问题:
As much as is reasonably practical, the hashCode method defined by
* class {@code Object} does return distinct integers for distinct
* objects. (This is typically implemented by converting the internal
* address of the object into an integer, but this implementation
* technique is not required by the
* JavaTM programming language.)
*
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.System#identityHashCode
*/
public native int hashCode();
因此,new Point(1,2)将不会被视为等于new Point(1,2),因此永远不会从中检索到Map。
2020-11-01