2015-04-29 33 views
2

优先级队列的元素根据它们的 自然排序或排队构造 时间提供的比较器进行排序,具体取决于使用哪个构造函数。PriorityQueue是否保持自然顺序?

但是,在下面的示例中,当我一次打印整个队列时,队列的元素按随机顺序打印。另一方面,如果我逐个轮询元素,它们会按照自然顺序打印。

有人可以解释我这种模棱两可的行为吗?或者我错过了什么?

public class QueueExample { 


    public static class Employee implements Comparable<Employee>{ 
     private int id; 
     private String name; 

     public Employee(int id, String name){ 
      this.id=id; 
      this.name=name; 
     } 

     public String toString(){ 
      return "id:"+id+" name:"+name; 
     } 

     public int compareTo(Employee emp){ 
      return name.compareTo(emp.name); 
     } 

    } 

    public static void main(String[] args) { 


     Queue<Employee> priority=new PriorityQueue<Employee>(); 

     priority.add(new Employee(101, "Atlas")); 
     priority.add(new Employee(102, "Ztlas")); 
     priority.add(new Employee(101, "Ftlas")); 
     priority.add(new Employee(101, "Ptlas")); 

     System.out.println(priority); 

     System.out.println(priority.poll()); 
     System.out.println(priority.poll()); 
     System.out.println(priority.poll()); 
     System.out.println(priority.poll()); 

    } 

} 

输出:

[ID:101名:阿特拉斯,ID:101名:Ptlas,ID:101名:Ftlas,ID:102 名:Ztlas]

ID:101名:阿特拉斯

ID:101名:Ftlas

ID:10 1名:Ptlas

ID:102名:Ztlas

回答

2

的位进一步向下在the documentation它说:

在方法迭代器(提供)的迭代器并不保证遍历元件以任何特定顺序排列优先级队列。

由于AbstractCollectiontoString(其中PriorityQueue继承)返回迭代顺序的一串,你从它那里得到任何特定的顺序。