【发布时间】:2016-11-07 03:54:59
【问题描述】:
我为 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;}? -
所以每次我做PriorityQueue.peek()时都会调用比较方法; ?因此使用更新的哈希映射/数组列表?是的,感谢您指出...'='不应该在那里
标签: java hashmap priority-queue comparator