好吧,我有一个带有多个实例变量的对象,我想对其进行排序,所以我读到我必须实现一个比较器类并使用它。
基本上它是一个以 PlaneSeats 对象作为其成员的平面类。 PlaneSeats 有 SeatID、CustomerID
我想按 CustomerID 打印占用的座位,有人知道怎么做吗?
//This Prints it by SeatID (Since it starts from 0)
for (int i = 0; i < seat.length; i++) {
if (seat[i].isOccupied()) {
System.out.println("SeatID " + seat[i].getSeatID() + " assigned to CustomerID " + seat[i].getCustomerID());
}
}
我失败的比较器代码如下:但我希望不要使用单独的类,希望是这样的 array.sort 函数?
import java.util.*;
public class Comparator implements Comparator<Plane> {
public int compare(Plane CustomerID[], Plane CustomerID[]) {
}
}
最佳答案
Arrays.sort(CustomerID, new Comparator<Plane>() {
public int compare(Plane p1, Plane p2) {
PlaneSeat ps1 = p1.getPlaneSeat();
PlaneSeat ps2 = p2.getPlaneSeat();
return ps1.getSeatID().compareTo(ps2.getSeatID());
}
});
这将根据 SeatId 进行排序。如果您想根据 CustomerId 进行排序,请将 getSeatID() 替换为 getCustomerID()。
关于java - 我的比较器类不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22287279/