PriorityQueue主要源码解析

简介:PriorityQueue优先队列,是Queue的实现类,但不具有先进先出的特点,而是根据自然排序或者自定义排序进行内部排序的,自然排序下(如存储Integer,String)会根据从小到大排序,自定义排序可以根据自己定义的比较方法排序。

1.Priority的底层是数组,初始化长度为11,下面是PriorityQueue的主要创建方法

    private static final int DEFAULT_INITIAL_CAPACITY = 11;

    private transient Object[] queue;

    //调用无参构造时初始化一个长度为11的数组
    public PriorityQueue() {
        this(DEFAULT_INITIAL_CAPACITY, null);
    }

    //直接指定数组长度
    public PriorityQueue(int initialCapacity) {
        this(initialCapacity, null);
    }

    //指定数组长度和比较器
    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;
    }

2.添加元素:add(E e)和offer(E e),两个方法其实是一样的,add方法内部就是调用offer方法

添加一个元素时,先判断当前元素加入是否越界,即用参数size(表示当前数组里的元素个数)判断是否大于队列长度,若大于则调用grow()方法扩展队列,然后将size+1,若元素为空,将元素放在首位,否则调用siftUp()方法将元素存入数组


    public boolean add(E e) {
        return offer(e);
    }

    public boolean offer(E e) {
        if (e == null)
            throw new NullPointerException();
        modCount++;
        int i = size;
        if (i >= queue.length)
            grow(i + 1);
        size = i + 1;
        if (i == 0)
            queue[0] = e;
        else
            siftUp(i, e);
        return true;
    }

 队列扩展方法

 private void grow(int minCapacity) {
        int oldCapacity = queue.length;
        // 当原数组长度小于64,每次将长度+2,否则扩展成原来的1.5倍
        int newCapacity = oldCapacity + ((oldCapacity < 64) ?
                                         (oldCapacity + 2) :
                                         (oldCapacity >> 1));

        // 若新数组长度大于MAX_ARRAY_SIZE,则调用hugeCapacity比较minCapacity是否大于MAX_ARRAY_SIZE,若大于就把新数组长度赋为Integer.MAX_VALUE,否则为MAX_ARRAY_SIZE
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        //然后将队列中的元素复制到新数组中
        queue = Arrays.copyOf(queue, newCapacity);
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

 siftUp()将元素存入数组

    // 判断是否有自定义比较器,没有则有自然排序
    private void siftUp(int k, E x) {
        if (comparator != null)
            siftUpUsingComparator(k, x);
        else
            siftUpComparable(k, x);
    }

    //自然排序:k即数组最后元素的下标,从后往前遍历,有元素比x大的,即往后移一位,知道有元素比x小,对出循环,将x插入
    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;
    }
    //自定义排序
    private void siftUpUsingComparator(int k, E x) {
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            if (comparator.compare(x, (E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = x;
    }

3.删除元素

poll():删除并返回队列头的元素,如果没有元素可取,返回null

remove():删除并返回队列头的元素,如果没有元素可取,报异常

remove(Object o):遍历数组查找元素的下标,删除下标

peek():返回队列头的元素,不删除

    //将第一个元素删除,然后将后面的元素往前移,将最后的元素赋为null
    public E poll() {
        if (size == 0)
            return null;
        int s = --size;
        modCount++;
        E result = (E) queue[0];
        E x = (E) queue[s];
        queue[s] = null;
        if (s != 0)
            siftDown(0, x);
        return result;
    }

    public E remove() {
        E x = poll();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

    public boolean remove(Object o) {
        int i = indexOf(o);
        if (i == -1)
            return false;
        else {
            removeAt(i);
            return true;
        }
    }

    public E peek() {
        if (size == 0)
            return null;
        return (E) queue[0];
    }

siftDown():将元素往前移

    private void siftDown(int k, E x) {
        if (comparator != null)
            siftDownUsingComparator(k, x);
        else
            siftDownComparable(k, x);
    }

    private void siftDownComparable(int k, E x) {
        Comparable<? super E> key = (Comparable<? super E>)x;
        int half = size >>> 1;        // loop while a non-leaf
        while (k < half) {
            int child = (k << 1) + 1; // assume left child is least
            Object c = queue[child];
            int right = child + 1;
            if (right < size &&
                ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0)
                c = queue[child = right];
            if (key.compareTo((E) c) <= 0)
                break;
            queue[k] = c;
            k = child;
        }
        queue[k] = key;
    }

    private void siftDownUsingComparator(int k, E x) {
        int half = size >>> 1;
        while (k < half) {
            int child = (k << 1) + 1;
            Object c = queue[child];
            int right = child + 1;
            if (right < size &&
                comparator.compare((E) c, (E) queue[right]) > 0)
                c = queue[child = right];
            if (comparator.compare(x, (E) c) <= 0)
                break;
            queue[k] = c;
            k = child;
        }
        queue[k] = x;
    }

4.例子


import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;

public class QueueTest {
	public static void main(String[] args) {
        //自然排序
		PriorityQueue<Integer> queue=new PriorityQueue<>();//初始化长度为11
		queue.offer(1);
		queue.add(1);
		queue.add(3);
		queue.add(2);
		int i=0;
		while(i++<10){
//			System.out.println(queue.peek());//输出1,1,1,1,...,1,1
//			System.out.println(queue.poll());//输出1,2,3,null,null,null,...,用poll时,如果队列为空,即返回null
//			System.out.println(queue.remove());//输出1,2,3,然后报异常
		}
		
		//自定义排序,引入自定义比较器,否则会报类转换异常
		PriorityQueue<Student> students=new PriorityQueue<>(10, new Comparator<Student>() {

			@Override
			public int compare(Student o1, Student o2) {
				// TODO Auto-generated method stub
				return o1.getAge()-o2.getAge();
			}
		});
		students.add(new Student(10, "张三"));
		students.add(new Student(8, "李四"));
		students.add(new Student(12, "王五"));
		for(Student student:students){
			System.out.println(student);
		}
		
		Iterator<Student> iterator = students.iterator();
		while(iterator.hasNext()){
			Student next = iterator.next();
			System.out.println(next.getAge()+"=="+next.getName());
		}
		
		
	}
}

Student类

package newCode;

public class Student {
	private int age;
	private String name;
	public Student(int age,String name) {
		// TODO Auto-generated constructor stub
		this.age=age;
		this.name=name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [age=" + age + ", name=" + name + "]";
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值