gpt4 book ai didi

java - 按升序排列数组列表

转载 作者:行者123 更新时间:2023-11-29 04:03:16 25 4
gpt4 key购买 nike

我有一个对象数组列表,每个对象都包含一个年/月/日/小时属性。我最终想要做的是创建一个新的多维数组,其中包含一组按小时递增的每个对象。所以例如,我想要的最终数组的一个例子是:

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

不过,我很难弄清楚如何在 Java 中正确排序数组列表。在将它们插入最终数组之前,我如何按升序对数组列表中的每个部分(年、月、日、小时)进行排序?

谢谢。

最佳答案

要对集合进行排序,您可以这样调用:

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

MyDate 类需要实现 Comparable 接口(interface),这需要实现“int compareTo(object o)”方法。

在“compareTo”方法中,您可以编写代码调用年、月等的 getter,直到确定当前对象是小于、等于还是大于对象“o"被传递到 compareTo 方法。

例子:

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
}

关于java - 按升序排列数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2045562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com