gpt4 book ai didi

java - 似乎无法按日期对对象数组进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 10:39:42 24 4
gpt4 key购买 nike

class newPlanner{

private newAppointment[] Appoint = new newAppointment[20];

newPlanner(){
newAppointment obj1 = new newAppointment("Mar",4,17,30,"Quiz 1");

newAppointment obj2 = new newAppointment("Apr",1,17,30,"Midterm");

newAppointment obj3 = new newAppointment("May",6,17,30,"Quiz 2");

newAppointment obj4 = new newAppointment("Jun",3,17,30,"Final");

Appoint [0] = obj4;
Appoint [1] = obj3;
Appoint [2] = obj2;
Appoint [3] = obj1;

}

public void runMethod(){
boolean answer = true;

while (answer) {
System.out.println("Select an Option. ");
System.out.println(" 1. Add Appointment ");
System.out.println(" 2. List Appointment ");
System.out.println(" 3. Delete Appointment ");
System.out.println(" 4. Exit ");

这是我的代码,我需要创建一个方法来移动数组元素以插入新约会并删除约会。该数组需要按日期排序,但我似乎无法得到它,请帮助

最佳答案

您可以使用 Arrays.sort(T[] a,Comparator<? super T> c) 对数组进行就地排序,其中T是你的Appointment类。

您将需要实现 Comparator Appointment的接口(interface)。如果您的 Appointment 这会容易得多类(class)参加了 Date 构造函数中的对象;那么你的比较器就是:

Arrays.sort(appointments, new Comparator<Appointment>{

@Override
public int compare(Appointment appointment1, Appointment appointment2){
return appointment1.getDate().compareTo(appointment2.getDate());
}
});

您可以确定 Appointment 的日期类如下:

public class Appointment{
/**
* three letter month
*/
private final String month;

/**
* one to two digit day e.g. 1 or 12,
*/
private final int day;

/**
* two digit military time hour e.g. 01, 11, 17
*/
private final int hour;

/**
* lazily instantiated appointment Date
*/
private Date date;

//..

public class Appointment(String month, int day, int hour /*other parameters*/){
this.month = month;
this.day = day;
this.hour = hour;

calculateDate();
}

private void caculateDate(){
String dateString = String.format("%d %s 2018 %d",day,month,hour);
SimpleDateFormat dateFormat = new SimpleDateFormat("d MMM yyyy HH");

try{
this.date = dateFormat.parse(dateString);
}catch(Exception e){
e.printStackTrace();
}
}

public Date getDate(){
return date;
}
}

关于java - 似乎无法按日期对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49127504/

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