如何在 java 中按时间对对象列表进行排序

How to sort list of object by time in java

什么是最好的方法(快速),如何按时间(小时:分钟:秒)对我的对象列表进行排序;

我有对象列表:

ArrayList<myObject> test = new ArrayList<>();

我有 class:

public class myObject{

private final myTime actualTime;
private final String name;

public myObject(int hour, int minute, int second, String name){
     this.actualTime = new myTime(hour, minute, second);
     this.name = name;
}

private class myTime{
     private final hour, minute, second;
     public myTime(int hour, int minute, int second){
          this.hour=hour;
          this.minute = minute;
          this.second =second;
     }
}

}

创建测试对象:

test.add(new myObject(1, 0, 0, "Name1")); //1 hour, 0 minute, 0second...
test.add(new myObject(9, 0, 0, "Name2"));
test.add(new myObject(2, 0, 0, "Name3"));

//now i want sort, but i dont know how?
//i want print: Name2, Name3, Name1

希望,你理解我,谢谢你的建议。

编辑 1:

   @Override
        public int compareTo(Object t) {
            hourTmp = ((myTime) t).getHour();
            if (this.getHour() > hourTmp) {
                return 1;
            } else {
                return -1;
            }
        }

您可以使用 Collections.sort(List) method which will perform a merge sort for you. But before you can use it you should make your custom class implement Comparable

在实现 Comparable 时,您需要实现 compareTo(myClass o) 方法并在该方法内对您需要的任何成员执行比较。

Collections.sort 方法与提供的 Comparator 一起使用,或者让您的对象实现 Comparable.

以下是如何在 java 8 中创建 Comparator(在为时间值添加 getter 之后):

Comparator.comparingInt(myTime::getHour)
              .thenComparingInt(myTime::getMinute)
              .thenComparingInt(myTime::getSecond);