Java 接口中的 toString()、equals() 和 hashCode()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1718112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:51:06  来源:igfitidea点击:

toString(), equals(), and hashCode() in an interface

javainterfaceequalshashcodetostring

提问by J_Y_C

So, I have an interface with a bunch of methods that need to be implemented, the method names are irrelevant.

所以,我有一个接口,里面有一堆需要实现的方法,方法名称无关紧要。

The objects that implement this interface are often put into collections, and also have a special toString() format that I want them to use.

实现此接口的对象通常放入集合中,并且还有我希望它们使用的特殊 toString() 格式。

So, I thought it would be convenient to put hashCode(), equals(), and toString() into the interface, to make sure that I remember to override the default method for these. But when I added these methods to the interface, the IDE/Compiler doesn't complain if I don't have those three methods implemented, even though I explicitly put them in the interface.

所以,我认为将 hashCode()、equals() 和 toString() 放入接口会很方便,以确保我记得覆盖这些的默认方法。但是当我将这些方法添加到接口时,IDE/编译器不会抱怨如果我没有实现这三个方法,即使我明确地将它们放在接口中。

Why won't this get enforced for me? It complains if I don't implement any of the other methods, but it doesn't enforce those three. What gives? Any clues?

为什么这不会对我强制执行?如果我不实现任何其他方法,它会抱怨,但它不会强制执行这三个方法。是什么赋予了?有什么线索吗?

采纳答案by Adam Batkin

All objects in Java inherit from java.lang.Objectand Objectprovides default implementations of those methods.

Java 中的所有对象都继承自java.lang.Object并且Object提供了这些方法的默认实现。

If your interface contains other methods, Java will complain if you don't implement the interface fully by providing an implementation of those methods. But in the case of equals(), hashCode()and toString()(as well as a few others that you didn't mention) the implementation already exists.

如果您的接口包含其他方法,如果您没有通过提供这些方法的实现来完全实现该接口,Java 会抱怨。但是在equals(),hashCode()toString()(以及您没有提到的其他一些)的情况下,实现已经存在。

One way you might be able to accomplish what you want is by providing a different method in the interface, say, toPrettyString()or something like that. Then you can call that method instead of the default toString()method.

您可能能够完成所需的一种方法是在界面中提供不同的方法,例如,toPrettyString()或类似的方法。然后您可以调用该方法而不是默认toString()方法。

回答by ChssPly76

All 3 of those methods are defined by java.lang.Objectwhich is (implicitly) extended by all other classes; therefore default implementations for those methods exist and compiler has nothing to complain about.

所有这 3 个方法都是由java.lang.Objectwhich定义的,由所有其他类(隐式)扩展;因此这些方法的默认实现存在,编译器没有什么可抱怨的。

回答by Tordek

There's an implementation for those methods coming all the way from Object.

这些方法的实现一直来自Object.

回答by Steve McLeod

Any class that implements your interface also extends Object. Object defines hashCode, equals, and toString and has default implementations of all three.

任何实现您的接口的类也扩展了 Object。Object 定义了 hashCode、equals 和 toString,并且具有所有这三个的默认实现。

What you are trying to achieve is good, but not practicable.

你想要达到的目标是好的,但不切实际。

回答by Matt Ball

Your object already contains implementations of those three methods, because every object inherits those methods from Object, unless they are overridden.

您的对象已经包含这三个方法的实现,因为每个对象都从 Object 继承这些方法,除非它们被覆盖。

回答by Ken Bloom

Java only cares that the methods are defined somewhere. The interface doesn't force you to redefine the methods in new classes that inherit from the interface for the first time if they're already defined. Since java.lang.Objectalready implements these methods, your new objects conform to the interface even if they don't override these three methods on their own.

Java 只关心方法是否在某处定义。接口不会强制您在第一次从接口继承的新类中重新定义方法(如果它们已经定义)。由于java.lang.Object已经实现了这些方法,您的新对象即使不重写这三个方法也符合接口。

回答by StriplingWarrior

Other people have answered your actual question sufficiently. As far as a solution for your particular problem, you might consider creating your own methods (maybe getStringRepresentation, getCustomHashcode, and equalsObject), and have your objects extend a base class whose equals, toString, and hashCode methods call these methods.

其他人已经充分回答了您的实际问题。至于您的特定问题的解决方案,您可能会考虑创建自己的方法(可能是 getStringRepresentation、getCustomHashcode 和 equalsObject),并让您的对象扩展一个基类,该基类的 equals、toString 和 hashCode 方法调用这些方法。

This might defeat the purpose of using an interface in the first place, though. This is one of the reasons that some people have suggested that equals, toString, and hashCode should never have been included on the Object class in the first place.

不过,这可能会破坏使用接口的初衷。这就是一些人建议从一开始就不应将 equals、toString 和 hashCode 包含在 Object 类中的原因之一。

回答by Stephen C

It sounds like you want to forceyour classes to override the default implementations of those methods. If so, the way to do this is to declare an abstract superclass that has the methods declared as abstract. For example:

听起来您想强制您的类覆盖这些方法的默认实现。如果是这样,这样做的方法是声明一个抽象超类,该超类将方法声明为抽象。例如:

public abstract class MyBaseClass implements ... /* existing interface(s) */ {

    public abstract boolean equals(Object other);

    public abstract int hashCode();

    public abstract String toString();
}

Then change your current classes to extendthis class.

然后将您当前的课程更改extend为该课程。

This approach kind of works, but it is not an ideal solution.

这种方法有效,但不是理想的解决方案。

  • It can be problematic for an existing class hierarchy.

  • It is a bad idea to forceclasses that implement your existing interface to extend a specific abstract class. For example, you can change parameters in method signatures to use the abstract class rather than the existing interface(s). But the end result is less flexible code. (And people can find ways to subvert this anyway; e.g. by adding their own abstract subclass that "implements" the methods with a super.<method>(...)call!)

  • Imposing a particular class hierarchy / implementation pattern is short sighted. You cannot predict whether some future requirement change will mean that your restrictions cause difficulties. (This is why people recommend programming against interfaces rather than specific classes.)

  • 对于现有的类层次结构,这可能是有问题的。

  • 强制实现现有接口的类扩展特定的抽象类是一个坏主意。例如,您可以更改方法签名中的参数以使用抽象类而不是现有接口。但最终的结果是代码不太灵活。(而且人们无论如何都可以找到颠覆这一点的方法;例如,通过添加他们自己的抽象子类,通过super.<method>(...)调用“实现”这些方法!)

  • 强加特定的类层次结构/实现模式是短视的。您无法预测未来的某些需求更改是否意味着您的限制会造成困难。(这就是为什么人们推荐针对接口而不是特定类进行编程的原因。)



Back to your actual question about why your interface doesn't force a class to redeclare those methods:

回到关于为什么您的接口不强制类重新声明这些方法的实际问题:

Why won't this get enforced for me? It complains if I don't implement any of the other methods, but it doesn't enforce those three. What gives? Any clues?

为什么这不会对我强制执行?如果我不实现任何其他方法,它会抱怨,但它不会强制执行这三个方法。是什么赋予了?有什么线索吗?

An interface imposes the constraint that a concrete class implementing it has an implementation for each of the methods. However, it doesn't require that the class itselfimplements those methods. The method implementations can be inherited from a superclass. And in this case, that is what is happening. The methods inherited from java.lang.Objectsaftisfy the constraint.

接口强加了一个约束,即实现它的具体类对每个方法都有一个实现。但是,它不要求类本身实现这些方法。方法实现可以从超类继承。在这种情况下,这就是正在发生的事情。继承自的方法java.lang.Object满足约束。

JLS 8.1.5states the following:

JLS 8.1.5声明如下:

"Unless the class being declared is abstract, all the abstract member methods of each direct superinterface must be implemented (§8.4.8.1) either by a declaration in this class or by an existing method declaration inherited from the direct superclass or a direct superinterface, because a class that is not abstract is not permitted to have abstract methods (§8.1.1.1)."

“除非声明的类是抽象类,否则每个直接超接口的所有抽象成员方法都必须通过此类中的声明或从直接超类或直接超接口继承的现有方法声明来实现(第 8.4.8.1 节),因为非抽象类不允许具有抽象方法(第 8.1.1.1 节)。”

回答by Bozho

If you want to force overriding of equals() and hashCode(), extend from an abstract superclass, which defines these methods as abstract.

如果要强制覆盖 equals() 和 hashCode(),请从抽象超类扩展,该超类将这些方法定义为抽象方法。

回答by sazamsk

well if u have declared an interface in which by default all the methods are abstract and u do need to provide the functionality but when u implement it in the subclass, then u provide the implementation right. as you can see that every class is the subclass of one superclass(put simply Object is superclass of all the classes) so if u have a class implementing an interface, u need to provide implementation for the methods. but a thing needs to be remembered here that.

好吧,如果您声明了一个接口,其中默认情况下所有方法都是抽象的,并且您确实需要提供功能,但是当您在子类中实现它时,那么您提供了实现权。正如你所看到的,每个类都是一个超类的子类(简单地说,Object 是所有类的超类),所以如果你有一个实现接口的类,你需要提供方法的实现。但这里需要记住一件事。

irrespective of, if u didn't declare these methods in the interface, you still had this behavior for the subclass that implemented the interface in the first place.

不管怎样,如果你没有在接口中声明这些方法,你仍然对首先实现接口的子类有这种行为。

so if don't declare it, it still will be present and another thing is that since these methods and other methods of Object class are present for all the objects of classes, so there is no need for implementation.

所以如果不声明,它还是会存在的,另外,由于Object类的这些方法和其他方法对于类的所有对象都存在,所以不需要实现。