史上最简单的 java PriorityQueue入门Demo

PriorityQueue:

是一个无界的优先级队列,优先级由元素指定(实现Comparable接口)
或者由其构造函数指定一个Comparator。
通过poll或者peak获取优先级最高的元素.

演示代码:

package com.abc.test;


import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.PriorityQueue;


/**
 * 注意:以下测试用例只能单独执行.
 */
public class PriorityQueueTest {

    public static class MyElement implements Comparable {
        final int order;
        final String name;

        public MyElement(String name, int order) {
            this.name = name;
            this.order = order;
        }

        @Override
        public int compareTo(Object o) {
            return this.order - ((MyElement) o).order;
        }
    }

    PriorityQueue<MyElement> priorityQueue = new PriorityQueue<>();

    /**
     * 先准备3个元素,供每个测试用例使用.
     */
    @Before
    public void init() {
        priorityQueue.add(new MyElement("5", 5));
        priorityQueue.add(new MyElement("3", 3));
        priorityQueue.add(new MyElement("1", 1));
        priorityQueue.add(new MyElement("10", 10));
    }

    /**
     * Peek
     * 元素1最小.
     * size仍然是4.
     */
    @Test
    public void testPeek() {
        MyElement element = priorityQueue.peek();
        Assert.assertEquals(element.order, 1);
        Assert.assertEquals(priorityQueue.size(), 4);
    }

    /**
     * poll
     * 元素1 最小.
     * 最后还有3个元素.
     */
    @Test
    public void testPoll() {
        MyElement element = priorityQueue.poll();
        Assert.assertEquals(element.order, 1);
        Assert.assertEquals(priorityQueue.size(), 3);
    }

    /**
     * clear
     */
    @Test
    public void testClear() {
        priorityQueue.clear();
        Assert.assertEquals(priorityQueue.size(), 0);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值