列表按升序和降序排序的规则如何? [英] How is the rule for sorting a list in ascending order and descending order?

查看:79
本文介绍了列表按升序和降序排序的规则如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试了解使用Comparable进行排序的方式.我有类Activity实现Comparable接口.我正在尝试了解activity.finish-this.finish;以降序排序,以及this.finish-activity.finish如何以升序排序.我对于首先使用什么进行升序和降序感到困惑?

I have been trying to understand how sorting using Comparable works. I have class Activity implementing Comparable interface. I am trying to understand how activity.finish-this.finish; sorts in descending order and how this.finish-activity.finish sorts in ascending order. I am confused about what to use first for sorting in ascending and descending?

class Activity implements Comparable {
    int start;
    int finish;

    public Activity(int start, int finish) {
        this.start = start;
        this.finish = finish;
    }

    @Override
    public int compareTo(Object o) {
        Activity activity = (Activity) o;
        return  activity.finish-this.finish;
    }
}

public class ActivitySelectionProblem {
    public static void main(String[] args) {
        int start[]  =  {1, 3, 0, 5, 8, 5};
        int finish[] =  {2, 4, 10, 7, 9, 9};

        List<Activity> list = new ArrayList<>();
        for(int i = 0 ; i < start.length ; i++){
            list.add(new Activity(start[i], finish[i]));
        }

        Collections.sort(list);
    }
}

推荐答案

这很hacky. compareTo的合同 是比较结果较小时返回小于 0 ,大于则返回 0 0 相等时.代码的作用并不明显.相反,我会使用 Integer.compare(int,int) -类似

It's hacky. The contract for compareTo is that it returns less than 0 when the result of comparison is less, greater than 0 when greater and 0 when equal. It is not obvious what the code does. Instead, I would use Integer.compare(int, int) - something like

@Override
public int compareTo(Object o) {
    return Integer.compare(this.finish, ((Activity) o).finish);
}

这篇关于列表按升序和降序排序的规则如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆