读priorityQueen源码_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 读priorityQueen源码

读priorityQueen源码

 2017/8/7 12:31:18  红领巾丶  程序员俱乐部  我要评论(0)
  • 摘要://先看构造方法。publicPriorityQueue(){this(DEFAULT_INITIAL_CAPACITY,null);}publicPriorityQueue(intinitialCapacity,Comparator<?superE>comparator){if(initialCapacity<1)thrownewIllegalArgumentException();this.queue=newObject[initialCapacity];this
  • 标签:源码
class="java">
//先看构造方法。
public PriorityQueue() {
        this(DEFAULT_INITIAL_CAPACITY, null);
    }

public PriorityQueue(int initialCapacity,
                         Comparator<? super E> comparator) {
       
        if (initialCapacity < 1)
            throw new IllegalArgumentException();
        this.queue = new Object[initialCapacity];
        this.comparator = comparator;
    }

 public PriorityQueue(Collection<? extends E> c) {
        if (c instanceof SortedSet<?>) {
	   //传入的是SortedSet
            SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
            this.comparator = (Comparator<? super E>) ss.comparator();
            initElementsFromCollection(ss);
        }
	//判断是否是PriorityQueue的子类
        else if (c instanceof PriorityQueue<?>) {
            PriorityQueue<? extends E> pq = (PriorityQueue<? extends E>) c;
            this.comparator = (Comparator<? super E>) pq.comparator();
            initFromPriorityQueue(pq);
        }
        else {
            this.comparator = null;
            initFromCollection(c);
        }
    }


private void initElementsFromCollection(Collection<? extends E> c) {
        //因为是SortedSet天然就有顺序所以直接复制数组过来
        Object[] a = c.toArray();
        // If c.toArray incorrectly doesn't return Object[], copy it.可能会出BUG。
        if (a.getClass() != Object[].class)
	  //重新创建一个数组
            a = Arrays.copyOf(a, a.length, Object[].class);
        int len = a.length;
	//不明白
        if (len == 1 || this.comparator != null)
            for (int i = 0; i < len; i++)
                if (a[i] == null)
                    throw new NullPointerException();
        this.queue = a;
        this.size = a.length;
    }


private void initFromPriorityQueue(PriorityQueue<? extends E> c) {
        //实际类型是PriorityQueue
        if (c.getClass() == PriorityQueue.class) {
            this.queue = c.toArray();
            this.size = c.size();
        } else {

            initFromCollection(c);
        }
    }

 private void initFromCollection(Collection<? extends E> c) {
        initElementsFromCollection(c);
        heapify();
    }

 private void heapify() {
        for (int i = (size >>> 1) - 1; i >= 0; i--)
            siftDown(i, (E) queue[i]);
    }


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

//有比较器的排序
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;
    }

//无比较器的排序
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;
    }


//add方法增加元素
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 siftUp(int k, E x) {
        if (comparator != null)
            siftUpUsingComparator(k, x);
        else
            siftUpComparable(k, 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;
    }
private void grow(int minCapacity) {
        int oldCapacity = queue.length;
        // 小于64扩容2倍+2否则扩容50%。
        int newCapacity = oldCapacity + ((oldCapacity < 64) ?
                                         (oldCapacity + 2) :
                                         (oldCapacity >> 1));
        // 超过了数组最大值
        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;
    }

 private void siftUp(int k, E x) {
        if (comparator != null)
            siftUpUsingComparator(k, x);
        else
            siftUpComparable(k, x);
    }

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

//获取头元素但是不移除如果队列为空返回null
 public E peek() {
        if (size == 0)
            return null;
        return (E) queue[0];
    }


//取出头元素如果队列为空返回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 boolean remove(Object o) {
        int i = indexOf(o);
        if (i == -1)
            return false;
        else {
            removeAt(i);
            return true;
        }
    }

private int indexOf(Object o) {
        if (o != null) {
            for (int i = 0; i < size; i++)
                if (o.equals(queue[i]))
                    return i;
        }
        return -1;
    }

  private E removeAt(int i) {
        assert i >= 0 && i < size;
        modCount++;
        int s = --size;
        if (s == i) // removed last element
            queue[i] = null;
        else {
            E moved = (E) queue[s];
            queue[s] = null;
            siftDown(i, moved);
            if (queue[i] == moved) {
                siftUp(i, moved);
                if (queue[i] != moved)
                    return moved;
            }
        }
        return null;
    }

//清空所有元素
public void clear() {
        modCount++;
        for (int i = 0; i < size; i++)
            queue[i] = null;
        size = 0;
    }

//返回指定类型的数组元素
 public <T> T[] toArray(T[] a) {
       //如果传入的数组长度小于队列长度直接新建一个队列装入队列中的所有元素
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(queue, size, a.getClass());
	 //大于直接copy
        System.arraycopy(queue, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }


/**总结:PriorityQueen采用二叉堆实现。至于什么事二叉堆参考这篇博客。http://www.cnblogs.com/tstd/p/5125949.html。
*/
发表评论
用户名: 匿名