我知道 PriorityQueue 是一个sorted 的集合 集合元素 是有顺序的 
类似的还有 Treeset 等 我查阅了API  toString() 方法 上面写的
返回此 collection 的字符串表示形式。该字符串表示形式由 collection 元素的列表组成,这些元素按其迭代器返回的顺序排列,并用方括号 ("[]") 括起来。相邻元素由字符 ", "(逗号加空格)分隔。
所以我的理解是 应该按照 迭代的顺序 返回  应该是[-3,0,6,9]
但是却出现了意外的结果 [-3,0,9,6] 。
后来网上也有人问类似的问题 但是始终没有解决
同学也都不会
希望CSDN的高手 帮我看一下
PriorityQueue a=new PriorityQueue();
a.offer(6);
a.offer(-3);
a.offer(9);
a.offer(0);
System.out.println(a);//这里为什么是 输出[-3,0,9,6}呢 

解决方案 »

  1.   

    楼主,它只是说toString的顺序是按照iterator的返回顺序
    但是PriorityQueue的iterator返回的顺序是不定的The string representation consists of a list of the collection's elements in the
    order they are returned by its iterator.This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()). 
      

  2.   


    谢谢大神  但是我就费解了 他这个 sorted 的意义 体现在哪里呢 
    既然是随机顺序
    难不成 在集合内部的保存 顺序是有序的  但是输出 迭代 就变成了无序的了
      

  3.   

    PriorityQueue是个基于优先级堆的极大优先级队列。
    此队列按照在构造时所指定的顺序对元素排序,既可以根据元素的自然顺序来指定排序(参阅 Comparable)PriorityQueue a = new PriorityQueue();
    a.offer(6);
    a.offer(-3);
    a.offer(9);
    a.offer(0);
    System.out.println(a); while (!a.isEmpty()) {
    System.out.print(a.poll() + ",");
    }
      

  4.   

    我想它内部数据结构是有序的,只是通过toString方式输出未必有序吧有时间要研究一下它iterator的next方法了
    public E next() {
                if (expectedModCount != modCount)
                    throw new ConcurrentModificationException();
                if (cursor < size)
                    return (E) queue[lastRet = cursor++];
                if (forgetMeNot != null) {
                    lastRet = -1;
                    lastRetElt = forgetMeNot.poll();
                    if (lastRetElt != null)
                        return lastRetElt;
                }
                throw new NoSuchElementException();
            }