是的,您可以创建一个
Comparator来创建排序策略,或者定义实现
Comparable的类的自然顺序
作为旁注:
It is strongly recommended, but not strictly required that
(x.compareTo(y)==0) == (x.equals(y))
使用比较器的示例:
class MyClass {
private Color color;
private String someOtherProperty;
public static final Comparator colorComparator = new MyComparator();
//getter and setter
static class MyComparator implements Comparator{
@Override
public int compare(MyClass o1, MyClass o2) {
// here you do your business logic, when you say where a color is greater than other
}
}
}
并在客户端代码中.
例:
List list = new ArrayList<>();
//fill array with values
Collections.sort(list, MyClass.colorComparator );
如果你想定义你的类的自然顺序,只需定义
public class MyClass implements Comparable{
@Override
public int compareTo(MyClass o) {
// do business logic here
}
}
并在客户端代码中:
Collections.sort(myList); // where myList is List