Is there any reason to implement Java for other types util. Comparable?

Classes that implement comparable < T > usually implement it for themselves, such as

class MyInteger implements Comparable<MyInteger> { ... }
class MyString implements Comparable<MyString> { ... }

But nothing can stop you from implementing it for different types:

class MyString implements Comparable<MyInteger> { ... }

This will allow you to compare mystring with myinteger

As described in the Javadoc, comparable aims to simulate natural sorting, i.e. total order. Therefore, in order to have antisymmetry, the parameter type of CompareTo should be the same as the type defining the method

But does the implementation class have any practical use (abuse) for sometype to implement comparable < othertype >?

Update: the answers provided by Joni and I give practical examples of comparable < supertypes > Implicit implementation, that is, your class passes the location where the interface is implemented It would be interesting to know if anyone has an example of using it explicitly

Solution

If there is a parent / child relationship, you will find this For example, the enum class implements comparable < E > e is a type parameter All enumerations share this CompareTo implementation

Clarification: enum < concreteclass > implements comparable < concreteclass > If it follows this pattern, you want it to implement comparable < enum < concreteclass > >

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>