欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Prioprity源码分析--priority如何实现优先级排序

程序员文章站 2022-04-21 21:11:32
目录本文围绕的核心问题:priority是怎么实现的根据优先级排序?Demo源码分析:offer方法siftUp方法siftUpUsingComparator方法接口Comparator中的compare方法(默认比较器)我自定义的compare方法siftUpComparable方法本文围绕的核心问题:priority是怎么实现的根据优先级排序?Demopublic class Demo { public static void main(St.....

目录

本文围绕的核心问题:priority是怎么实现优先级排序?

Demo

源码分析:

offer方法

siftUp方法

siftUpUsingComparator方法

接口Comparator中的compare方法(默认比较器)

自定义的compare方法

siftUpComparable 方法


本文围绕的核心问题:priority是怎么实现优先级排序?

Demo

public class Demo {
    public static void main(String[] args) {
        //需求:priority中age越大优先级越高
        PriorityQueue<Student> priorityQueue = new PriorityQueue<>(2, new StudentComparator());
        Student s1 = new Student("jack", 2200);
        Student s2 = new Student("Tom", 223);
        priorityQueue.offer(s1);
        priorityQueue.offer(s2);
        Student poll = priorityQueue.poll();
        System.out.println(poll.name+":"+poll.age);
    }
}


public class StudentComparator implements Comparator<Student> {
    @Override
    public int compare(Student current, Student middle) {
        if (current.age>middle.age)
            return -1;
        else if (current.age<middle.age)
            return 1;
        else
            return 0;
    }
}
  

public class Student {
    String name;
    int age;
    public Student(String name,int age){
        this.name=name;
        this.age=age;
    }
}

源码分析:

  • 底层的队列依靠数组实现
  • 内部有比较器,可以在构造函数中指定自定义的比较器
public class PriorityQueue<E> extends AbstractQueue<E>
    implements java.io.Serializable {
    ...    
    /**
     * Priority queue represented as a balanced binary heap: the two
     * children of queue[n] are queue[2*n+1] and queue[2*(n+1)].  The
     * priority queue is ordered by comparator, or by the elements'
     * natural ordering, if comparator is null: For each node n in the
     * heap and each descendant d of n, n <= d.  The element with the
     * lowest value is in queue[0], assuming the queue is nonempty.
     */
    transient Object[] queue; // non-private to simplify nested class access

    /**
     * The number of elements in the priority queue.
     */
    private int size = 0;

    /**
     * The comparator, or null if priority queue uses elements'
     * natural ordering.
     */
    private final Comparator<? super E> comparator;

    ...

    public PriorityQueue(int initialCapacity,
                         Comparator<? super E> comparator) {
        // Note: This restriction of at least one is not actually needed,
        // but continues for 1.5 compatibility
        if (initialCapacity < 1)
            throw new IllegalArgumentException();
        this.queue = new Object[initialCapacity];
        this.comparator = comparator;
    }
}

 

offer方法

    public boolean offer(E e) {
        if (e == null)
            throw new NullPointerException();
        modCount++;
        //i记录当前数组长度
        int i = size;
        //越界扩容处理
        if (i >= queue.length)
            grow(i + 1);
        //加入新元素e,长度+1
        size = i + 1;
        //第一个元素直接放置
        if (i == 0)
            queue[0] = e;
        //之后加入队列的元素进行筛选
        else
            siftUp(i, e);
        return true;
    }

 

siftUp方法

private void siftUp(int k, E x) {
    //判断是否有比较器
    if (comparator != null)
        //使用自定义的比较器进行插入
        siftUpUsingComparator(k, x);
    else
        //使用默认比较器
        siftUpComparable(k, x);
}

 

siftUpUsingComparator方法

private void siftUpUsingComparator(int k, E x) {
    //从当前位置,不断的往前遍历,通过比较器修改每个位置
    while (k > 0) {
        //parent是中间位置的角标
        int parent = (k - 1) >>> 1;
        Object e = queue[parent];
        //调用比较器的compare方法,比较当前要插入的元素和中间位置的大小关系
        if (comparator.compare(x, (E) e) >= 0)
            //默认情况下构建的是一个完全二叉树实现的小顶堆。
            //我们这里通过自定义的比较器构建一个大顶堆,在比较器中需要设置当前元素小于中间元素返回1,才能跳出循环
            break;
        //否则把当前元素放置到中间位置,    
        queue[k] = e;
        //k的值变成中间位置,方便后续不断的调整优先队列中前半部分保持优先级的降序
        k = parent;
    }
    //确定好优先级位置后放置x
    queue[k] = x;
}

 

接口Comparator中的compare方法(默认比较器)

public interface Comparator<T> {
    /**
     * Compares its two arguments for order.  Returns a negative integer,
     * zero, or a positive integer as the first argument is less than, equal
     * to, or greater than the second.<p>
     * 比较两个参数进行排序,返回负数,零,正整数,
     * 分别代表第一个参数小于,等于,大于第二个参数
     *...
     */
    int compare(T o1, T o2);
}

 

自定义的compare方法

目标:(让队列最后是降序排序)

// 给age降序排序
public class StudentComparator implements Comparator<Student> {
    @Override
    public int compare(Student current, Student middle) {
        if (current.age>middle.age)
            return -1;
        else if (current.age<middle.age)
            return 1;
        else
            return 0;
    }
}

 

siftUpComparable 方法

代码类似siftUpUsingComparator,使用的是默认比较器

    private void siftUpComparable(int k, E x) {
        Comparable<? super E> key = (Comparable<? super E>) x;
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            if (key.compareTo((E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = key;
    }

 

 

 

本文地址:https://blog.csdn.net/qq_38783664/article/details/110471807