2

java~优先级队列PriorityQueue

 2 years ago
source link: https://www.cnblogs.com/lori/p/15385338.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

PriorityQueue是一种支持排序的优先级队列,你入队列的对象需要实现Comparable或Comparator接口,或者它本身支持自然排序,如Integer,Long这些类型(这些类型也都实现了Comparable接口)。

优先级队列底层的数据结构其实是一颗二叉堆,什么是二叉堆呢?我们来看看下面的图(a为大顶堆,b为小顶堆)

  • 在这里我们会发现以下特征:
  1. 二叉堆是一个完全二叉树
  2. 根节点总是大于左右子节点(大顶堆),或者是小于左右子节点(小顶堆)。

java代码例子

  • 定义一个对象,实现Comparable接口
@Data
  static class Customer implements Comparable<Customer> {
    private int id;
    private String name;

    public Customer(int i, String n) {
      this.id = i;
      this.name = n;
    }

    public int getId() {
      return id;
    }

    public String getName() {
      return name;
    }

    @Override
    public int compareTo(Customer o) {
      if (this.id < o.id) return -1; // 小于目标值,返回-1表示升序,即-1表示数值由小到大的排序
      else if (this.id == o.id) return 0;
      else return 1;
    }
  }
  • 添加测试用例
  @Test
  public void test() {
    Queue<Customer> priorityQueue = new PriorityQueue<>();
    priorityQueue.add(new Customer(1, "zhansan"));
    priorityQueue.add(new Customer(2, "lisi"));
    priorityQueue.add(new Customer(4, "wangwu"));
    while (!priorityQueue.isEmpty()) {
      Customer cust = priorityQueue.poll();
      System.out.println("Processing Customer =" + cust.toString());
    }
  }
  • 测试结果,按着id的升序出队列
Processing Customer =PriorityQueueTest.Customer(id=1, name=zhansan)
Processing Customer =PriorityQueueTest.Customer(id=2, name=lisi)
Processing Customer =PriorityQueueTest.Customer(id=4, name=wangwu)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK