什么时候类应该是 Comparable 和/或 Comparator? [英] When should a class be Comparable and/or Comparator?
问题描述
我见过同时实现Comparable 和Comparator 的类.这是什么意思?为什么我要使用一个而不是另一个?
I have seen classes which implement both Comparable and Comparator. What does this mean? Why would I use one over the other?
推荐答案
以下文字来自比较器与可比较
具有可比性
一个可比较的对象能够将自己与另一个对象进行比较.类本身必须实现 java.lang.Comparable
接口,以便能够比较其实例.
A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable
interface in order to be able to compare its instances.
比较器
比较器对象能够比较两个不同的对象.该类不是比较它的实例,而是比较其他一些类的实例.此比较器类必须实现 java.util.Comparator
接口.
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator
interface.
这篇关于什么时候类应该是 Comparable 和/或 Comparator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!