Different usage of comparable interface and comparator interface

Both can be used to define comparison methods and then used in sorting.

Comparable is the interface inherited by the class itself

Comparator defines a sorted class outside the real class

Comparatively speaking, I think comparator is more flexible, but comparable is more convenient.

For example, chestnuts:

Output:

For some classes that have been written, such as string, we certainly can't modify its CompareTo () method, so we can write a custom comparator.

Output:

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
分享
二维码
< <上一篇
下一篇>>