سؤال

I'm trying to create a priorityqueue which keeps its elements(Pairs of integers) in the reverse of the natural order. I've found severeal tips on the site, but in every case it gave the same wrong order.

    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);
    }

Here is the Pair class

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;

}

}

If I use the "new PriorityQueue()" constructor, it gives a proper natural ordering. Thanks for your time, Mark

هل كانت مفيدة؟

المحلول

From the docs for PriorityQueue.iterator():

Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order.

If you want to get them out in priority order, keep calling poll() until it returns null:

Pair pair;
while((pair = pq.poll()) != null) {
    System.out.println(pair.value);
}

That prints 58, 55, 23, 15, as you were looking for.

نصائح أخرى

instead of "return a2.value.compareTo(a1.value);" you should directly use ((a2.value > a1.value)? 1: ((a2.value ==a1.value) ? 0 : -1));

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top