在我的PriorityQueue中,我有2種類型的客戶,VIP和常規。我想先服務VIP,然後定期。Java PriorityQueue自定義比較器
如果客戶ID爲< 100它被認爲是VIP。
如果客戶是貴賓,他去在隊列
的VIP部分結束時如果客戶是有規律的,他去在整個隊列的末尾。
換句話說,我想布爾VIP值進行排序,同時保留在客戶前來順序
這裏是我的Order類
public class Order implements Comparable<Order> {
private final int customerID;
private final int amount;
private final boolean vip_status;
public Order(int customerID, int amount) {
this.customerID = customerID;
this.amount = amount;
this.vip_status = customerID < 100 ? true : false;
}
@Override
public int compareTo(Order o) {
if (vip_status && !o.vip_status) {
return -1;
}
if (!vip_status && o.vip_status)
return 1;
return 0;
}
public int getCustomerID() {
return customerID;
}
public int getAmount() {
return amount;
}
public boolean isVip_status() {
return vip_status;
}
}
這裏是我試圖填補隊列:
import java.util.PriorityQueue;
public class MyPriorityQueue {
public static void main(String[] args) {
PriorityQueue<Order> queue = new PriorityQueue<>();
Order o1 = new Order(1, 50);
Order o2 = new Order(5, 30);
Order o3 = new Order(4, 10);
Order o4 = new Order(150, 5);
Order o5 = new Order(2, 5);
Order o6 = new Order(200, 5);
queue.add(o1);
queue.add(o2);
queue.add(o3);
queue.add(o4);
queue.add(o5);
queue.add(o6);
while(!queue.isEmpty()){
Order s = queue.poll();
System.out.printf("VIP Status: %s CustomerID: %s Amount: %s%n",
s.isVip_status(), s.getCustomerID(), s.getAmount());
}
}
}
結果是我得到(這是錯誤的):
VIP Status: true CustomerID: 1 Amount: 50
VIP Status: true CustomerID: 5 Amount: 30
VIP Status: true CustomerID: 2 Amount: 5
VIP Status: true CustomerID: 4 Amount: 10
VIP Status: false CustomerID: 150 Amount: 5
VIP Status: false CustomerID: 200 Amount: 5
這是我希望看到(客戶ID 2和4應該是他們來到在同一順序):
VIP Status: true CustomerID: 1 Amount: 50
VIP Status: true CustomerID: 5 Amount: 30
VIP Status: true CustomerID: 4 Amount: 10
VIP Status: true CustomerID: 2 Amount: 5
VIP Status: false CustomerID: 150 Amount: 5
VIP Status: false CustomerID: 200 Amount: 5
更新:我不要,除了VIP任何其他列排序想要的。我不想添加「日期」,因爲它感覺像是一個黑客,而不是理解Java如何工作。
您的compareTo不比較數額,以及它必須這樣做才能成功。 –
將最後一次返回值從'return 0;'更改爲'return Integer.compare(amount,o.amount);' –
@HovercraftFullOfEels OP希望訂單成爲插入隊列的順序,並且數量似乎只是無關的數據。 – RealSkeptic