更新时间:2023-11-26 14:57:58
似乎HashMap不使用equals方法(我可能错了,如果我的测试是错误的)。
It seems that HashMap doesn't use the equals method (I may be wrong, if so my tests are wrong).
它使用等于
,但是首先使用 hashCode
。它只会打扰在具有相同哈希码的密钥上调用等于
- 这就是它如何管理效率。这不是问题,只要您的 hashCode
和等于
方法服从 java中指定的合同.lang.Object
。
It does use equals
, but it uses hashCode
first. It will only bother calling equals
on keys with the same hash code - that's how it manages to be efficient. That's not a problem so long as your hashCode
and equals
method obey the contract specified in java.lang.Object
.
我正在密钥中存储时间戳,并希望使它如果时间戳差异不超过定义的数量(例如1000 ms),则2个键是相等的。
I am storing timestamp in the key, and would like to make it so that 2 keys are equals if there timestamp difference does not exceed a defined amount (let say 1000 ms).
你不能这样做。它违反了平等的合同,因为你不能有传递性。假设我们有三个键x,y和z具有以下时间戳:
You can't do that. It violates the contract of equals, because you can't have transitivity. Suppose we have three keys x, y, and z with the following timestamps:
x 400
y 1200
z 2000
根据您的描述, x.equals(y)
将为true, y.equals(z)
将为true,但 x.equals(z)
将是错误的,因此违反了 Object.equals
By your description, x.equals(y)
would be true, y.equals(z)
would be true, but x.equals(z)
would be false, thus violating the contract of Object.equals
.
equals方法实现等价关于非空对象引用:
The equals method implements an equivalence relation on non-null object references: