我试图创建一个priorityqueue,它的元素(整数对)与自然顺序相反。我在网站上发现了一些严重的提示,但是在任何情况下,它都会给出相同的错误顺序。PriorityQueue包含“对”,以相反的数字顺序Java
PriorityQueue<Pair> pq = new PriorityQueue(4,
new Comparator<Pair>() {
public int compare(Pair a1, Pair a2) {
return a2.value.compareTo(a1.value);
}
});
pq.add(new Pair(1,15));
pq.add(new Pair(2,58));
pq.add(new Pair(3,55));
pq.add(new Pair(7,23));
Iterator<Pair> it = pq.iterator();
while(it.hasNext()) {
System.out.println(it.next().value);
}
这里是Pair类
public class Pair implements Comparable {
public Integer name;
public Integer value;
public Pair(int name, int value) {
this.name = name;
this.value = value;
}
public int getname(){
return name;
}
public int getvalue() {
return value;
}
public int compare(Pair o1, Pair o2) {
Pair a1 = (Pair)o1;
Pair a2 = (Pair)o2;
if(a1.value>a2.value) {
return 1;
}
else if(a1.value<a2.value) {
return -1;
}
return 0;
}
@Override
public int hashCode() {
int hash = 3;
return hash;
}
@Override
public boolean equals(Object o) {
Pair a2 = (Pair)o;
return this.name == a2.name && this.value == a2.value;
}
public int compareTo(Object o) {
Pair a2 = (Pair)o;
if(this.value>a2.value) {
return 1;
}
else if(this.value<a2.value) {
return -1;
}
return 0;
}
}
如果我使用了“新的优先级Queue()“的构造函数,它给出了适当的自然排序。 感谢您的时间, 马克
哇,谢谢你的快速回答!我从来没有猜到,迭代器不会工作......尤其是因为它与自然顺序一起工作。 – 2011-03-27 20:40:41
@ jon-spectet:它确实给出了正确的顺序,但是将我的队列留空。编写自己的迭代器是唯一的途径? – 2011-03-29 10:02:06
@ alex-murphy:可能;老实说,我不确定。 – 2011-03-29 10:24:11