JAVA优先级队列元素输出顺序测试

时间:2023-03-08 17:46:45
JAVA优先级队列元素输出顺序测试
package code.test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue; /**
* 实验表明,在java中:
* 1.toString()方法或迭代元素:优先级队列打印或者迭代,得到的输出顺序都为堆结构数组的顺序,大致有序但不完全保证顺序
* 2.使用poll()方法:元素整体有序,但由于堆排序是不稳定排序,优先级相同的元素,不会保持原来的顺序输出
* 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;
}
}