2011-03-27 66 views
0

我试图创建一个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()“的构造函数,它给出了适当的自然排序。 感谢您的时间, 马克

回答

3

从文档为PriorityQueue.iterator()

返回在此队列中的元素的迭代器。迭代器不会以任何特定顺序返回元素。

如果你想出来的优先顺序,保持通话poll(),直到它返回null

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

,打印58,55,23,15,你要寻找的。

+0

哇,谢谢你的快速回答!我从来没有猜到,迭代器不会工作......尤其是因为它与自然顺序一起工作。 – 2011-03-27 20:40:41

+0

@ jon-spectet:它确实给出了正确的顺序,但是将我的队列留空。编写自己的迭代器是唯一的途径? – 2011-03-29 10:02:06

+0

@ alex-murphy:可能;老实说,我不确定。 – 2011-03-29 10:24:11

0

而不是“return a2.value.compareTo(a1.value);” 你应该直接使用((a2.value> a1.value)?1:((a2.value == a1.value)?0:-1));

+1

为什么?你的代码显然难以阅读,国际海事组织。是的,它避免了潜在的拳击 - 但我不会在此基础上改变它。原始比较代码正常工作。 – 2011-03-27 17:26:56