java++新建map_当我创建对象的新实例作为键时,Java HashMap.get()返回null

小编典典

为了在上面详细说明我的评论,您的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值