如何比较ArrayList和ArrayList之间的Int?(爪哇)
我现在正在给日历编代码。我将约会保存在另一个ArrayList中的两个不同ArrayList中
字符串(主题、地点、人物)进入另一个ArrayList中的第一个ArrayList=arStr
整数(日期和时间)进入另一个ArrayList=arInt中的第二个ArrayList
创建约会时,我希望根据日期对其进行排序。因此,如果我想添加新约会,它应该保存在outter列表中已保存约会的上方或下方(取决于时间)。如果已保存的日期晚于新的日期,则应将其放在outter列表中。完成后,我想将字符串约会连接到Int约会
我的问题是,我找不到一种方法,以这种方式来排序,谁能帮我:)
public class Calender
{
public static ArrayList<ArrayList<Integer>> arInt = new ArrayList<ArrayList<Integer>>();
public static ArrayList<ArrayList<String>> arStr = new ArrayList<ArrayList<String>>();
public static Scanner read = new Scanner(System.in);
public static int counter = 0; // counts all made appointments
public static void main (String[]args)
{
//Adding Arrylists for space
arInt.add(new ArrayList());
arStr.add(new ArrayList());
arInt.add(new ArrayList());
arStr.add(new ArrayList());
// This is one Appointment ( Subject, Year, Month, Day, Hour )
// Already saved Appointment
counter++;
arStr.get(0).add("3.Liste");
arInt.get(0).add(2017);
arInt.get(0).add(2);
arInt.get(0).add(8);
arInt.get(0).add(16);
// new Appointment
counter++;
String betreff = "1. Appointment";
int year = 2017;
int month = 2;
int day = 8;
int hours = 15;
// How to compare these Variables with the first Appointment and save it accordigly ?
}
}
# 1 楼答案
首先,在其他的
ArrayList
中有ArrayList
,在这种情况下,这些是完全不必要的。删除这些选项将大大简化您的代码:下一步,您需要统一这两个列表。您当前拥有的是一个日期列表和一个单独的约会名称列表。您需要一个约会列表。为此,您需要编写一个约会类:
然后,您将能够创建以下内容的ArrayList:
为了能够以各种方式对列表进行排序,您可以使用:
您需要编写自己的“比较器”来实现这一点。这基本上是一个比较两个对象以确定哪一个先到的函数。一月一日在一月三日之前吗?那种事
有关更多信息,请参阅this answer或谷歌“编写自定义比较器java”
# 2 楼答案
我的建议是创建新类
Appointment
,给它分配一个LocalDateTime
,并让日历存储该类型的列表,例如List<Appointment> appointments = new ArrayList<>()
之后,使用内置排序方法和您自己的比较器可以轻松地对约会进行排序:
appointments.sort((a1, a2) -> a1.date.isBefore(a2.date));)
在任何情况下,我建议您先做一个关于面向对象设计的教程,比如https://www.tutorialspoint.com/object_oriented_analysis_design/index.htm