两个相等的对象是否必须具有相同的 toString 输出?

Do two equal objects have to have the same toString output?

两个相等的对象是否必须具有相同的 toString 输出?

在代码中,一般情况下必须满足以下条件吗?

if(o1.equals(o2))
  return o1.toString().equals(o2.toString()) // always true?

我问是因为我刚刚写了一个 toString 方法,上面的语句 成立。我在文档中找不到任何提示,但我想确保我的 toString 方法没有违反任何合同规则。

不,它们不必具有相同的 toString() 输出才能相等。 Java 中没有规定对象本身及其 toString() 方法的 equals() 方法必须为真。

equals() 与其他方法的唯一约定是 hashCode():

Note that it is generally necessary to override the hashCode method whenever this method [equals] is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

无论其他方法如何,它所拥有的合同是:

  • 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.

来源:https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object-

编辑:一些人说 Joshua Bloch 的 Effective Java 说 toString() 方法应该使用与 equals() 方法相同的字段。这不是真的。他说:

While it isn’t as important as obeying the equals and hashCode contracts (Item 8, Item 9), providing a good toString implementation makes your class much more pleasant to use.

他归类为“良好实施”的是:

When practical, the toString method should return all of the interesting information contained in the object, as in the phone number example just shown. It is impractical if the object is large or if it contains state that is not conducive to string representation. Under these circumstances, toString should return a summary such as “Manhattan white pages (1487536 listings)” or “Thread[main,5,main]”.

所以不,它与 equals() 方法没有任何关系。

toString 没有约定,只有equals 和hashCode。从我的角度来看,这也没有意义。

假设 o1 和 o2 属于 classPerson{},那么您得到的只是引用的字符串。

没有这个要求。 equalshashCode 之间存在依赖关系:相等的对象必须 return 具有相同的 hashCode 值。 toString 仅用于打印对象。

没有 "requirement" hashCodeequals 相匹配,只有这样做的最佳实践,否则您的程序将毫无意义。与 toString 相同。它应该与 equals 一致,如果使用,也应该与 compareTo 一致。有关基本原理,请参阅 Joshua Bloch 的 Effective Java。告诉你其他情况的人需要阅读那本书,因为他们错了。