[英]Design a compareTo that can sort in ascending or descending order
I have a class States that is an object that contains a name, and a list of states that we consider edges. 我有一个状态类,它是一个包含名称的对象,以及一个我们认为是边的状态列表。 I would like to sort this list of edges by name, in both ascending and descending order. 我想按名称对边缘列表进行升序和降序排序。 I had an idea of overriding the compareTo function and leveraging Collections.sort(). 我有一个重写compareTo函数并利用Collections.sort()的想法。
public class State {
private String name;
private ArrayList<States> edges;
...
public ArrayList<States> getEdges(){
return edges;
}
public int compareTo(State s, int type){
switch(type){
case 0:
// we want ascending order, return as normal
return this.name.compareTo(s.getName());
case 1:
// we want descending order, negate our answer
return -this.name.compareTo(s.getName());
}
return -1;
}
Is it possible to use Collection.sort(), but be able to provide the 'type' parameter to specify whether I want ascending or descending order? 是否可以使用Collection.sort(),但能够提供'type'参数来指定我要升序还是降序? If not, what are some other ways I can accomplish this? 如果没有,我还有什么其他方法可以做到这一点?
You could make the list descending by reversing it: 您可以通过反转列表使列表降序:
Collection<?> collection = ...;
Collections.reverse(collection);
PS: why is your class named States? PS:您的班级为何被命名为国家? From what I see the class represents a State... 从我看来,班级代表着一个国家...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.