简体   繁体   English

按升序对数组列表进行排序

[英]sort arraylist in ascending order

i have an arraylist of objects, each containing a year/month/day/hour property.我有一个对象数组列表,每个对象包含一个年/月/日/小时属性。 what i'm ultimately trying to do, is create a new multidimensional array that contains a group of every object by incrementing hour.我最终想要做的是创建一个新的多维数组,通过增加小时来包含一组每个对象。 so for instance, an example of the final array i'd want is:例如,我想要的最终数组的一个例子是:

array: [0]
            [0] 01:04:00, 4-10-09
            [1] 01:15:00, 4-10-09
       [1]
            [0] 02:25:00, 4-10-09
       [2]
            [0] 06:14:00, 4-10-09
            [1] 06:27:00, 4-10-09
       [3]   
            [0] 04:03:00, 4-11-09
            [1] 04:11:00, 4-11-09

i'm having a difficult time figuring out to properly sort arraylists in java though.不过,我很难弄清楚在 Java 中正确排序数组列表。 how could i sort each section (year,month,day,hour) within the arraylist in ascending order, before inserting them into an final array?在将它们插入最终数组之前,我如何按升序对数组列表中的每个部分(年、月、日、小时)进行排序?

thanks.谢谢。

Check out Comparators http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparator.html查看比较器http://java.sun.com/j2se/1.4.2/docs/api/java/util/Comparator.html

Comparator is an interface with the method compare(Object1, Object2) in which you can compare the dates You then define your own comparator object which implement comparator and then use Collections.sort(Arraylist, comparator) Comparator 是带有 compare(Object1, Object2) 方法的接口,您可以在其中比较日期然后定义自己的比较器对象,该对象实现比较器,然后使用 Collections.sort(Arraylist, Comparator)

To sort a collection you can make a call like this:要对集合进行排序,您可以像这样拨打电话:

List<MyDate> dates = ... 
Collections.sort(dates);

The MyDate class will need to implement the interface Comparable which will require the method "int compareTo(object o)" to be implemented. MyDate 类将需要实现接口 Comparable,这将需要实现方法“int compareTo(object o)”。

In the "compareTo" method, you can then write the code which will call the getters for the year, month, and so on until it figures out whether the current object is less than, equal to or greater than the object "o" being passed into the compareTo method.在“compareTo”方法中,您可以编写代码来调用年、月等的getter,直到它确定当前对象是否小于、等于或大于对象“o”传递给 compareTo 方法。

Example:示例:

public int compareTo(Object o) {
    MyDate otherDate = (MyDate) o;
    int thisYear = this.getYear();
    int otherYear = otherDate.getYear();
    if (thisYear < otherYear) return -1;
    if (thisYear > otherYear) return 1;
    // Now try the month, then day etc
}

Implement the comparable interface on your time/date object.在您的时间/日期对象上实现可比较的接口。 Then it would be as easy as doing Collections.sort然后就像做 Collections.sort 一样简单

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

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