AbstractQueue虚拟类重点
- AbstractQueue虚拟类继承自AbstractCollection虚拟类,AbstractCollection虚拟类是使用子类实现的size()和iterator()两个方法,实现一个集合类的查询、添加、删除、批量操作,AbstractCollection虚拟类源码可以看我这篇文章 AbstractCollection
- AbstractQueue实现Queue接口,Queue接口定义了6个方法,分为三类插入、删除、检索,每类有两个方法,一个是操作不成功抛出异常如add、remove、element,另一个是操作不成功返回特殊值null如offer、poll、peek,Queue接口源码可以看我这篇文章 Queue
- AbstractQueue虚拟类子类必须实现offer、peek、poll、size、iterator五个方法,offer、peek、poll三个方法是AbstractQueue要求的,size、iterator两个方法是AbstractCollection要求的
- AbstractQueue虚拟类里面的定义方法都是用子类实现的offer、peek、poll三个方法实现的
AbstractQueue虚拟类方法
| 方法名 | 作用 |
|---|---|
| boolean add(E e) | 在队尾添加一个元素,不成功抛异常,成功返回true,使用offer实现 |
| E remove() | 获取并删除此队列的头,不成功抛异常,成功返回元素,使用poll实现 |
| E element() | 获取但不删除此队列的头,不成功抛异常,成功返回元素,使用peek实现 |
| void clear() | 从此队列中删除所有元素,循环调用poll实现 |
| boolean addAll(Collection c) | 将集合c中所有元素添加进队列,循环调用add实现 |
AbstractQueue虚拟类源码
package java.util; public abstract class AbstractQueueextends AbstractCollection implements Queue { protected AbstractQueue() { } public boolean add(E e) { if (offer(e)) return true; else throw new IllegalStateException("Queue full"); } public E remove() { E x = poll(); if (x != null) return x; else throw new NoSuchElementException(); } public E element() { E x = peek(); if (x != null) return x; else throw new NoSuchElementException(); } public void clear() { while (poll() != null) ; } public boolean addAll(Collection extends E> c) { if (c == null) throw new NullPointerException(); if (c == this) throw new IllegalArgumentException(); boolean modified = false; for (E e : c) if (add(e)) modified = true; return modified; } }



