その要素(整数のペア)を自然な順序の逆に保つ優先度付きキューを作成しようとしています。私はサイトで厳しいヒントを見つけましたが、いずれの場合も同じ間違った順序を与えました。
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;
}
}
「newPriorityQueue()」コンストラクターを使用すると、適切な自然順序付けが行われます。お時間をいただきありがとうございます、マーク