자연 순서와 반대 방향으로 요소 (정수 쌍)를 유지하는 우선 순위 대기열을 만들려고합니다. 사이트에서 심한 도움말을 발견했지만, 모든 경우에 똑같은 잘못된 주문을 내 렸습니다. 여기 "쌍"을 역순으로 포함하는 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);
}
는 쌍 클래스
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() "생성자를 사용하면 적절한 자연 순서가 지정됩니다. 시간에 대한 감사합니다, PriorityQueue.iterator()
에 대한 문서에서 마크
와우 맨, 빠른 답변 주셔서 감사합니다! 나는 iterator가 작동하지 않을 것이라는 것을 결코 짐작하지 않았을 것이다 ... 특히 그것이 자연 순서와 함께 작동했기 때문에. –
@ jon-skeet : 적절한 순서를 제공하지만 내 대기열을 비워 둡니다. 자체 반복자를 작성하는 것이 유일한 방법입니다. –
@ alex-murphy : 가능합니다; 나는 정직하지 못하다. –