本文介绍了遍历PriorityQueue不会产生有序结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import java.util.*;
class Priority{  
public static void main(String args[]){  

PriorityQueue<String> queue=new PriorityQueue<String>();  
queue.add("Amit");  
queue.add("Vijay");  
queue.add("Karan");  
queue.add("Jai");  
queue.add("Rahul");  

System.out.println("head:"+queue.element());  
System.out.println("head:"+queue.peek());  

System.out.println("iterating the queue elements:");  
Iterator itr=queue.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  
}  

queue.remove();  
queue.poll();  

System.out.println("after removing two elements:");  
Iterator itr2=queue.iterator();  
while(itr2.hasNext()){  
System.out.println(itr2.next());  
}  

}  
}  

Output:head:Amit
   head:Amit
   iterating the queue elements:
   Amit
   Jai
   Karan
   Vijay
   Rahul
   after removing two elements:
   Karan
   Rahul
   Vijay

您好,我在尝试学习Java中集合下的优先级队列(如上所示)。现在,由于输出,我真的很困惑。我不明白输出是如何这样产生的(如上所示)。

Hi there i was trying to learn priority queue which comes under collections in java(shown above). Now i'm really confused, because of the output. I cant understand how the output came like this (which is shown above).

iterating the queue elements:
   Amit
   Jai
   Karan
   Vijay
   Rahul

vijay在rahul之前是如何出现的?我猜想,如果拉乌尔必须按字母顺序排列,那么它必须早于vijay。

how does vijay came before rahul? if its in alphabetical order rahul must come before vijay i guess.

所以谁能解释程序和方法element()内部发生了什么?我找不到该方法。

so can anyone explain whats happening inside the program and method element() what does it do?. I couldnt find that method.

推荐答案

PriorityQueue 不存储元素按排序顺序排列,但它允许您按排序顺序从中获取元素。只是确保按照其使用的顺序,最前面的元素是最小的元素。

PriorityQueue doesn't store the elements in sorted order, but it allows you to get the elements from it in sorted order. It just makes sure that the the element at the head is the least element as per the ordering used for it.

因此,如果您存储多个数字- 2、1、4、3、6、8 ,它将确保 1 是您要删除的下一个元素。然后,当您删除 1 时,它会将 2 移到头部。不必担心其余元素的顺序。

So, if you store multiple numbers - 2, 1, 4, 3, 6, 8, it will make sure that 1 is the next element you remove. Then when you remove 1, it moves 2 to head. It doesn't bother about the ordering of rest of the elements.

这篇关于遍历PriorityQueue不会产生有序结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 20:35