public E peek(){if(size ==0)//队列中没有元素,返回nullreturn null;return(E) queue[0];}//继承自AbstractQueue的类方法public E element(){
E x =peek();if(x != null)return x;elsethrownewNoSuchElementException();}
删除元素:
remove(): 删除队顶元素,底层调用的是poll;队列为空则抛出异常;==>父类提供方法;
poll() : 删除队顶元素,队列为空返回null;
//父类提供方法public E remove(){
E x =poll();if(x != null)return x;elsethrownewNoSuchElementException();}//实现父类Queue接口的方法;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;//将最后一个角标元素置为nullif(s !=0)//队列中有元素siftDown(0, x);//重新调整小根堆return result;}privatevoidsiftDown(int k, E x){if(comparator != null)//有没有给自定义比较器siftDownUsingComparator(k, x);elsesiftDownComparable(k, x);}//默认比较器调整小根堆privatevoidsiftDownComparable(int k, E x){
Comparable<?super E> key =(Comparable<?super E>)x;//int half = size >>>1;//得到中值坐标//因为x是最后有元素的角标,所以 half坐标正好是它的父节点,//父节点肯定是小于子节点的,我们一直是用x值进行比较的,如果到最后一次循环,//实际上是没有必要在去进行比较while(k < half){//当前坐标小于中值坐标int child =(k <<1)+1;//左孩子 2n+1
Object c = queue[child];int right = child +1;//右孩子,2n+2 //比较两个孩子,得到其中最小的一个孩子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;}//自定义比较器调整根堆privatevoidsiftDownUsingComparator(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;}