我有PriorityQueue用例,它生成
3
1
1
1
5
0这是密码
import java.util.*;
class Someclass
{
public static class IntegerWr
implements Comparable<IntegerWr>
{
Integer val;
IntegerWr(Integer val)
{
this.val = val;
}
public void change(Integer nval)
{
this.val = nval;
}
@Override
public int compareTo(IntegerWr iw)
{
return val.compareTo(iw.val);
}
@Override public String toString()
{
return ""+val;
}
}
public static void main (String[] args)
{
PriorityQueue<IntegerWr> pq = new PriorityQueue<>();
pq.add(new IntegerWr(3));
System.out.println(pq.peek());
IntegerWr iw1 = new IntegerWr(1);
pq.add(iw1);
System.out.println(pq.peek());
pq.add(new IntegerWr(4));
System.out.println(pq.peek());
pq.add(new IntegerWr(2));
System.out.println(pq.peek()); //must output 1, and does so
iw1.change(5); //change value of element that is actually on peek
System.out.println(pq.peek()); //outputs 5 which is unexpected
pq.add(new IntegerWr(0));
System.out.println(pq.peek());
}
}似乎PriorityQueue只在insert上下订单。使用什么方法获取实际的peek()?
发布于 2016-03-22 10:16:41
PriorityQueue是队列的实现。如果我们查看队列接口,它有方法peek()、poll()、remove()。
peek()方法返回但不移除队列的头。
poll()方法移除并返回队列的头。从队列中移除哪个元素是队列的排序策略的函数。
import java.util.*;
class Someclass
{
public static class IntegerWr
implements Comparable<IntegerWr>
{
Integer val;
IntegerWr(Integer val)
{
this.val = val;
}
public void change(Integer nval)
{
this.val = nval;
}
@Override
public int compareTo(IntegerWr iw)
{
return val.compareTo(iw.val);
}
@Override public String toString()
{
return ""+val;
}
}
public static void main (String[] args)
{
PriorityQueue<IntegerWr> pq = new PriorityQueue<>();
pq.add(new IntegerWr(3));
System.out.println(pq.peek());
IntegerWr iw1 = new IntegerWr(1);
pq.add(iw1);
System.out.println(pq.peek());
pq.add(new IntegerWr(4));
System.out.println(pq.peek());
pq.add(new IntegerWr(2));
System.out.println(pq.peek()); //must output 1, and does so
iw1.change(5); //change value of element that is actually on peek
System.out.println(pq.peek()); //outputs 5 which is unexpected
pq.add(new IntegerWr(0));
System.out.println(pq.peek());
System.out.println("Elements ordered");
Object o = null;
while ((o = pq.poll()) != null) //poll() method removes and return
//the head of the queue.
//Exactly which element is removed
//from the queue is a function
//of the queue's ordering policy
{
System.out.println(o);
}
}
}输出
3
1
1
1
5
0
Elements ordered
0
2
3
4
5要按顺序获取PriorityQueue 的元素,请使用poll()。
发布于 2016-03-21 12:24:29
您正在更改存储在队列中的对象内的值。队列不知道任何有关对象内容的信息。因此,当您对队列中的一个对象(如'iw1.change(5)')调用一个方法时,队列中什么都不知道。您需要存储一个替换对象,以便队列重新排序元素。
发布于 2016-03-21 12:30:02
而不是iw1.change(5);,请做:
pq.remove(iw1);
iw1.change(5);
pq.add(iw1);https://stackoverflow.com/questions/36130720
复制相似问题