简体   繁体   English

Comparable接口是带有其compareTo()方法的标记接口吗?

[英]How is the Comparable interface is marker interface, with its compareTo() method?

How is the Comparable interface is marker interface, even though it defines a compareTo() method? 即使Comparable接口定义了compareTo()方法,它也是标记接口吗? Please explain detail. 请详细说明。

A marker interface is just a design pattern. 标记界面只是一种设计模式。 So even if you read around "X is a marker interface" this doesn't really mean anything apart from "X is an interface with no methods declared". 因此,即使您阅读“ X是标记接口”,这也没有什么意思,除了“ X是没有声明方法的接口”。

Since Comparable<T> has one method then it is not used as a marker interface. 由于Comparable<T>有一种方法,因此它不用作标记接口。

A marker interface is useful when you want to attach data to a type to be able to use this data in specific situations, this is not the case of Comparable , which is used to provide an effective interface. 当您希望将数据附加到一种类型以便能够在特定情况下使用此数据时,标记接口很有用,而Comparable则不是这种情况,后者用于提供有效的接口。

I don't even think that the definition of marker interface is used in javadoc to describe empty intefaces such as Serializable (not sure about it though). 我什至不认为在javadoc中使用标记接口的定义来描述空的接口,例如Serializable (尽管不确定)。

It is not a marker interface. 它不是标记界面。 Marker interface in Java for eg Serializable, Clonnable and Remote are used to indicate something to compiler or JVM; Java中的标记接口(例如Serializable,Clonnable和Remote)用于指示编译器或JVM。 indicate a flag to compiler. 指示编译器的标志。

Quoting Wikipedia on Marker interface pattern (emphasis mine): Marker界面模式 (强调我的) 引用Wikipedia

[...] class implements a marker interface, and methods that interact with instances of that class test for the existence of the interface. 类实现了标记器接口,并且与该类实例进行交互的方法会测试该接口的存在。 Whereas a typical interface specifies functionality (in the form of method declarations) that an implementing class must support, a marker interface need not do so . 尽管典型的接口指定了实现类必须支持的功能 (以方法声明的形式),但是标记接口不必这样做 The mere presence of such an interface indicates specific behavior on the part of the implementing class. 仅仅存在这样的接口就表示实现类方面的特定行为 Hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used. 既可以充当标记并指定所需方法的混合接口是可能的,但是如果使用不当,可能会造成混淆。

That being said Comparable<T> can be called a marker interface, but it's confusing and I've never heard this before. 话虽如此, Comparable<T> 可以称为标记器接口,但令人困惑,我之前从未听说过。

I can't imagine a class testing whether some object implements Comparable<T> without actually down-casting and calling compareTo() . 我无法想象在没有实际向下转换并调用compareTo()情况下测试某些对象是否实现Comparable<T>的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM