0
我爲PriorityQueue編寫了一個比較器,以便根據HashMap中ArrayList中的第一個值給出最小值。更新傳遞給PriorityQueue的HashMap/ArrayList比較器
我的問題是,在我的程序的其餘部分,我需要更新/更改ArrayList中的第一個值。我不確定如何做到這一點,以確保優先隊列總是給我基於更新的正確結果?
感謝
public class MyComparator implements Comparator<Integer>{
HashMap<Integer, ArrayList<Integer>> hm;
public MyComparator(HashMap<Integer, ArrayList<Integer>> hm){
this.hm = hm;
}
@Override
public int compare (Integer num, Integer num1){
ArrayList<Integer> list = hm.get(num);
int w = list.get(0);
ArrayList<Integer> list1 = hm.get(num1);
int w1 = list1.get(0);
if(w1 - w == 0){
return 0;
}
if(w1 - w <= 0){
return 1;
}
else{
return -1;
}
}
}
它會給你在調用比較方法時的正確結果。另外,只是提及它不應該是'if(w1 - w <0){return 1;}'? – Thrasher
所以每次我做PriorityQueue.peek()時都會調用比較方法; ?因此使用更新後的哈希映射/數組列表?是的,謝謝你指出......'='不應該在那裏 – Lsldioo