简体   繁体   English

用Java对数组排序

[英]Sorting an array in java

I am having an range of time , i want to sort the time based on the starting time For Ex: 我有一个时间范围,我想根据Ex的开始时间对时间进行排序:

Range = {[3,5] , [1,10] ,[6,7] ,[4,10]}
After sorting
{ [1,10] , [3,5] , [4,10] , [6,10]}

How can it be done using Collections.sort or anyother method. 如何使用Collections.sort或任何其他方法来完成。
Does i have to define a class to sort ie 我需要定义一个类别进行排序吗

class interval{
int start;
int end;
}

i have above structure i want to sort it with respect to start; 我具有上述结构,我想就开始进行排序;
ie Collections.sort(interval) // with respect to start;

Use Collections.sort with a custom Comparator<T> : Collections.sort与自定义Comparator<T>

Collections.sort(times, new Comparator<interval>() {
    public int compare(interval a, interval b) {
        int res = Integer.compare(a.start, b.start);
        if (res != 0) return res;
        return Integer.compare(a.end, b.end);
    }
});

Another way of coding this would be implementing the Comparable<T> interface in the interval class. 对此进行编码的另一种方法是在interval类中实现Comparable<T>接口。

You have 2 options either implement Comparable for your class or use Comparator. 您有2个选项可以为您的类实现Comparable或使用Comparator。 Using java 8 syntax it will look like this 使用Java 8语法,它将看起来像这样

Collections.sort(list, (o1, o2) -> {
            int start =  Integer.compare(o1.getStart(), o2.getStart());
            int end =  Integer.compare(o1.getEnd(), o2.getEnd());
            if (start != 0) return start;
            else return end;
        });

To implement Comparable you should do like this 要实现可比,您应该这样做

    class interval implements Comparable<interval> {
@Override
    public int compareTo(interval o) {
        //the same logic as used in compartor
    }
}

Just a hint won't be writing code for you until you show some more effort 直到您付出更多努力,才有可能为您编写代码

Implement you own Comparator and pass this as an argument to Collections.sort 实现您自己的比较器,并将其作为参数传递给Collections.sort

Another thing to consider make sure you don't do new Comparator as this will keep making new instances of you comparator. 要考虑的另一件事是确保您不做新的Comparator,因为这将使您继续创建比较器的新实例。 You want to make it singleton. 您要使其单例。

To build on top of dasblinkenlight's answer, to achieve this by implementing the Comparable interface in the interval, do this 要建立在dasblinkenlight答案的基础上,要通过在间隔中实现Comparable接口来实现此目的,请执行此操作

class interval implements Comparable<interval> {
  // old code
  public int compare(interval a, interval b) {
    int res = Integer.compare(a.start, b.start);
    if (res != 0) return res;
    return Integer.compare(a.end, b.end);
  }
}

Note that it is customary to use capital case for class name, so change 'interval' to Interval. 请注意,习惯上使用大写字母作为类名,因此请将“ interval”更改为“ Interval”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM