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;
    }
}

 

转载于:https://www.cnblogs.com/chenggang816/p/7491712.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值