標籤:迭代 tostring 原來 main asn 輸出 new add priority
package code.test;import java.util.Comparator;import java.util.Iterator;import java.util.PriorityQueue;import java.util.Queue;/** * 實驗表明,在java中: * 1.優先順序隊列列印或者迭代,得到的輸出順序為堆結構數組的順序,大致有序但不完全保證順序 * 2.由於堆排序是不穩定排序,在優先順序相同的情況下,元素不會保持原來的順序輸出 * Created by cg on 2017/9/7. */public class PriorityQueueTest { public static void main(String[] args) { Queue<Integer> queue = new PriorityQueue<Integer>(); queue.add(1); queue.add(5); queue.add(3); queue.add(2); queue.add(8); queue.add(10); queue.add(23); queue.add(14); System.out.println(queue); //輸出:[1, 2, 3, 5, 8, 10, 23, 14] Iterator<Integer> iterator = queue.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " "); }//輸出:1 2 3 5 8 10 23 14 System.out.println(); Queue<Student> queue1 = new PriorityQueue<Student>(new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { return s1.age - s2.age; } }); queue1.add(new Student("a", 14)); queue1.add(new Student("b", 12)); queue1.add(new Student("c", 12)); queue1.add(new Student("d", 12)); queue1.add(new Student("e", 12)); queue1.add(new Student("f", 13)); queue1.add(new Student("g", 11)); while (!queue1.isEmpty()){ System.out.println(queue1.poll()); } /*輸出 g:11 c:12 d:12 e:12 b:12 f:13 a:14 */ }}class Student{ String name; int age; public Student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return name + ":" + age; }}
JAVA優先順序隊列測試