【问题标题】:Design a compareTo that can sort in ascending or descending order设计一个可以升序或降序排序的 compareTo
【发布时间】:2016-06-02 09:34:24
【问题描述】:

我有一个 States 类,它是一个包含名称的对象,以及我们认为是边的状态列表。我想按名称对这个边列表进行升序和降序排序。我有一个重写 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;
     }

是否可以使用 Collection.sort(),但能够提供 'type' 参数来指定我想要升序还是降序?如果没有,我还有什么其他方法可以做到这一点?

【问题讨论】:

  • “如果没有,我还有什么其他方法可以做到这一点?”reverse 列表。

标签: java


【解决方案1】:

您可以通过反转列表来使列表降序:

Collection<?> collection = ...;
Collections.reverse(collection);

PS:为什么你的班级命名为States?从我看到的类代表一个状态......

【讨论】:

  • 这是一个doh!肯定的时刻。把清单倒过来……漂亮!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 2014-11-21
  • 1970-01-01
  • 2019-10-03
  • 2021-07-10
  • 1970-01-01
相关资源
最近更新 更多