gpt4 book ai didi

Java:实现类似问题

转载 作者:行者123 更新时间:2023-12-02 03:44:22 27 4
gpt4 key购买 nike

我是新来的,正在寻找有关我的代码的一些建议。我正在尝试使 arrayList ArrayList<patient> heartPatientArray = new ArrayList<patient>(); //heart patients 成为可能能够在patient's上进行排序arrivalTime

代码:

    class patient implements Comparable
{
int typeSickness; //1 for heart 2 for gastro 3 for bleeding
double arrivalTime; //what time they arrived SORT BY
int deathTime; // what time they are set to balk or die
int status; //0 for being cared for, 1 to n for location in line, -1 if dead
int personalNumberInLine; //personal number in line updated everytime someone enters the line
double timeSpentInQueue; //total time before they either died or were able to be treated
int idOfPerson; //unique id the person gets when entering the queue
boolean isAlive;

public patient(int sickness, double arrival, int ID) { //sets the patients sickness, time arrived, and ID
typeSickness=sickness;
arrivalTime=arrival;
idOfPerson = ID;
}
public int getTypeSickness() {
return typeSickness;
}
public void setTypeSickness(int typeSickness) {
this.typeSickness = typeSickness;
}
public double getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(double arrivalTime) {
this.arrivalTime = arrivalTime;
}
public int getDeathTime() {
return deathTime;
}
public void setDeathTime(int deathTime) {
this.deathTime = deathTime;
}

public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getNumberInLine() {
return personalNumberInLine;
}
public void setNumberInLine(int numberInLine) {
this.personalNumberInLine = numberInLine;
}
@Override
public int compareTo(patient one) {
if (this.getArrivalTime() < one.getArrivalTime()) {
return -1;
}
else if(this.getArrivalTime() > one.getArrivalTime()){
return 1;
}

return 0;
}

some code edited out for time's sake

我尝试根据网上找到的一些代码对其进行样式设置,但在 compareTo(patient one) 上收到错误删除覆盖符号,以及 class patient implements Comparable 上的错误告诉我必须使类抽象。

正确实现compareTo后,我将如何对 heartPatientArray 进行排序?

最佳答案

您正在实现 Comparable原始形式界面。正因为如此,compareTo需要 Object ,这解释了为什么您在尝试实现该接口(interface)时遇到错误。

相反,将您的类作为类型参数传递。

class patient implements Comparable<patient>

然后你的compareTo方法按原样将实现 Comparable<patient>正确地。

通常,Java 命名约定会要求将类名大写。

class Patient implements Comparable<Patient>

您可以使用以下方式对列表进行排序:

Collections.sort(heartPatientArray);

如果您想以相反的顺序对其进行排序,您可以指定:

Collections.sort(heartPatientArray, Comparator.reverseOrder());

一般来说,您可以通过传递 Comparator<Patient> 的实例来对它进行任意排序。 ,实现Comparatorcompare方法,注意将类型参数传递给 Comparable就像我们现在为 Comparable 所做的那样。然后传递 Comparator<Patient> 的实例作为 Collections.sort 的第二个参数.

关于Java:实现类似问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36459722/

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