且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否存在使用equals方法进行密钥检查的映射?

更新时间: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:


  • 它是反身:对于任何非空引用值x, x.equals(x)应该返回true。

  • 它是对称:对于任何非空参考值x和y,x.equals(y)应该返回true当且仅当y.equals(x)返回true时。

  • 它是传递:对于任何非空参考值x,y和z ,如果x.equals(y)返回true并且y.equals(z)返回true,那么x.equals(z)应该返回true。

  • 它是一致:对于任何非空参考值x和y,x.equals(y)的多次调用始终返回true或始终返回false,前提是在对象的equals比较中没有使用任何信息被修改。

  • 对于任何非空值参考值x,x.equals(null)应返回false。

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.