本文介绍了自动检查equals,hashCode和compareTo的一致性的技巧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很清楚合同需要确保 hashCode 等于等于 compareTo 一致。但是,这是。是否有任何工具,技术或库可以自动测试这种一致性?

I'm well aware of the contractual needs to make sure that hashCode is consistent with equals and that equals is consistent with compareTo. However, this is often violated in practice. Are there any tools, techniques, or libraries that can test for this consistency automatically?

我怀疑不幸的是答案是不,但它会很有用能够对这种可以使用库调用或框架的东西进行单元测试,而不是需要手动为每个重要的情况编写自定义测试。

I suspect unfortunately that the answer is "no," but it would be useful to be able to have a unit test for this sort of thing that could make use of a library call or framework rather than needing to write a custom test by hand for each case where it is important.

如果不清楚我的一致性是什么意思,对于 hashCode 等于我指的是以下内容:

In case it's not clear what I mean by consistency, for hashCode and equals I refer to the following:

对于等于 compareTo 我参考以下内容:

For equals and compareTo I refer to the following:


推荐答案

测试有一个名为我们用作单元测试的日常部分来测试等于 hashCode 。它的用法类似于

Guava's tests have a utility called EqualsTester which we use as an everyday part of our unit tests to test equals and hashCode. Its use looks like

new EqualsTester()
  .addEqualityGroup("hello", "h" + "ello")
  .addEqualityGroup("world", "wor" + "ld")
  .addEqualityGroup(2, 1 + 1)
  .testEquals();

它测试同一组中的所有值是否相等且具有相同的哈希码,即不同的组是相等,并且各种其他不变量都满足。您可以自己使用它,也可以只是借用它的想法。

which tests that all values in the same group are equal and have the same hash codes, that different groups are not equal, and that various other invariants are all satisfied. You could either use it yourself, or just borrow its ideas.

如果可以在不生成或明确指定测试值的情况下进行测试,我会非常惊讶,因为那样做似乎非常可能等同于暂停问题。

I would be extremely surprised if it was possible to test without generating or explicitly specifying test values, just because that seems very likely equivalent to the halting problem.

这篇关于自动检查equals,hashCode和compareTo的一致性的技巧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 23:03