为什么PriorityQueue里面的值在java中的poll方法之后改变? [英] Why do the values inside the PriorityQueue change after the poll method in java?

查看:401
本文介绍了为什么PriorityQueue里面的值在java中的poll方法之后改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码,输出在它下面为什么值5和6我的意思是在PriorityQueue中的poll方法后如何设置新的优先级在队列中)。我准备java认证考试,我总是倾向于选择错误的答案由于这个概念,任何帮助是欢迎。

This is the code and the output is below it why do the value "5" and "6" i mean how are the new priorities set after poll method in a PriorityQueue (similarly the other elements in the queue) . I am preparing for java certification exam and i always tend to choose the wrong answer due to this concept, any help is welcomed.

import java.util.*;

public class PriorityQueueDemo {
public static void main(String args[]) {
  // create priority queue
  PriorityQueue < Integer >  prq = new PriorityQueue < Integer > (); 

  // insert values in the queue
  for ( int i = 3; i  <  10; i++ ){  
     prq.add (new Integer (i)) ; 
  }

  System.out.println ( "Initial priority queue values are: "+ prq);

  // get the head from the queue
  Integer head = prq.poll();

  System.out.println ( "Head of the queue is: "+ head);

  System.out.println ( "Priority queue values after poll: "+ prq);
 }
}

输出:

Initial priority queue values are: [3, 4, 5, 6, 7, 8, 9]
Head of the queue is: 3
Priority queue values after poll: [4, 6, 5, 9, 7, 8]


推荐答案

这些值没有更改,只是以不同的顺序打印。

toString() > PriorityQueue 按 Iterator 返回元素的顺序返回。如果您阅读了 <$ c的Javadoc $ c> PriorityQueue#iterator() 您会看到以下内容:

The values haven't changed, they are just printed in a different order.
The toString() for PriorityQueue returns the elements in the order they are returned by its Iterator. If you read the Javadoc for PriorityQueue#iterator() you see the following:


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

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

打印输出,因为 PriorityQueue 不会以任何特定顺序,优先级或其他方式打印。

So, you can't draw any conclusions from your printouts, since no effort is being made by the PriorityQueue to print them in any particular order, by priority or otherwise.

这篇关于为什么PriorityQueue里面的值在java中的poll方法之后改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆