AbstractQueue简介

本文详细介绍了Java中Queue接口的抽象实现类AbstractQueue,包括其核心方法如add、remove、element等的功能与实现原理,以及如何通过子类实现具体队列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Queue接口定义:[url]http://donald-draper.iteye.com/blog/2363491[/url]
/*
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/

package java.util;

/**
* This class provides skeletal implementations of some {@link Queue}
* operations. The implementations in this class are appropriate when
* the base implementation does [i]not[/i] allow <tt>null</tt>
* elements. Methods {@link #add add}, {@link #remove remove}, and
* {@link #element element} are based on {@link #offer offer}, {@link
* #poll poll}, and {@link #peek peek}, respectively, but throw
* exceptions instead of indicating failure via <tt>false</tt> or
* <tt>null</tt> returns.
AbstractQueue提供了Queue的操作实现的基础。AbstractQueue可以作为不允许
元素为null时,Queue的简单实现。add,remove,element方法分别基于offer,
poll,peek的实现,但是当队列为null时,抛出异常,而不是返回false或null。

* <p>A <tt>Queue</tt> implementation that extends this class must
* minimally define a method {@link Queue#offer} which does not permit
* insertion of <tt>null</tt> elements, along with methods {@link
* Queue#peek}, {@link Queue#poll}, {@link Collection#size}, and
* {@link Collection#iterator}. Typically, additional methods will be
* overridden as well. If these requirements cannot be met, consider
* instead subclassing {@link AbstractCollection}.
*
Queue的实现必须实现offer方法,并且允许插入null;peek,poll,size方法最好
重写,如果这些要求不能满足,可以用AbstractCollection代替。
* <p>This class is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @since 1.5
* @author Doug Lea
* @param <E> the type of elements held in this collection
*/
public abstract class AbstractQueue<E>
extends AbstractCollection<E>
implements Queue<E> {

/**
* Constructor for use by subclasses.
*/
protected AbstractQueue() {
}

/**
* Inserts the specified element into this queue if it is possible to do so
* immediately without violating capacity restrictions, returning
* <tt>true</tt> upon success and throwing an <tt>IllegalStateException</tt>
* if no space is currently available.
*
* <p>This implementation returns <tt>true</tt> if <tt>offer</tt> succeeds,
* else throws an <tt>IllegalStateException</tt>.
*
* @param e the element to add
* @return <tt>true</tt> (as specified by {@link Collection#add})
* @throws IllegalStateException if the element cannot be added at this
* time due to capacity restrictions
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this queue
* @throws NullPointerException if the specified element is null and
* this queue does not permit null elements
* @throws IllegalArgumentException if some property of this element
* prevents it from being added to this queue
*/
添加一个元素,成功返回ture,否则抛出异常
public boolean add(E e) {
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}

/**
* Retrieves and removes the head of this queue. This method differs
* from {@link #poll poll} only in that it throws an exception if this
* queue is empty.
*
* <p>This implementation returns the result of <tt>poll</tt>
* unless the queue is empty.
*
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
*/
消费队列头元素,有则返回元素,为null,则抛出异常
public E remove() {
E x = poll();
if (x != null)
return x;
else
throw new NoSuchElementException();
}

/**
* Retrieves, but does not remove, the head of this queue. This method
* differs from {@link #peek peek} only in that it throws an exception if
* this queue is empty.
*
* <p>This implementation returns the result of <tt>peek</tt>
* unless the queue is empty.
*
* @return the head of this queue
* @throws NoSuchElementException if this queue is empty
*/
检查是否有元素,有则返回元素,无则抛出异常
public E element() {
E x = peek();
if (x != null)
return x;
else
throw new NoSuchElementException();
}

/**
* Removes all of the elements from this queue.
* The queue will be empty after this call returns.
*
* <p>This implementation repeatedly invokes {@link #poll poll} until it
* returns <tt>null</tt>.
*/
清空,循环poll,直到为空
public void clear() {
while (poll() != null)
;
}

/**
* Adds all of the elements in the specified collection to this
* queue. Attempts to addAll of a queue to itself result in
* <tt>IllegalArgumentException</tt>. Further, the behavior of
* this operation is undefined if the specified collection is
* modified while the operation is in progress.
*
* <p>This implementation iterates over the specified collection,
* and adds each element returned by the iterator to this
* queue, in turn. A runtime exception encountered while
* trying to add an element (including, in particular, a
* <tt>null</tt> element) may result in only some of the elements
* having been successfully added when the associated exception is
* thrown.
*
* @param c collection containing elements to be added to this queue
* @return <tt>true</tt> if this queue changed as a result of the call
* @throws ClassCastException if the class of an element of the specified
* collection prevents it from being added to this queue
* @throws NullPointerException if the specified collection contains a
* null element and this queue does not permit null elements,
* or if the specified collection is null
* @throws IllegalArgumentException if some property of an element of the
* specified collection prevents it from being added to this
* queue, or if the specified collection is this queue
* @throws IllegalStateException if not all the elements can be added at
* this time due to insertion restrictions
* @see #add(Object)
*/
//循环遍历集合元素,add到队列
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;
}
}

总结:
[color=green]AbstractQueue的add,remove,element方法分别基于offer,poll,peek的实现,但是当队列为null时,抛出异常,而不是返回false或null。offer,poll,peek,并没有实现待子类扩展。清空,循环poll,直到为空。addAll为循环遍历集合元素,add到队列;[/color]
附:AbstractCollection

[img]http://dl2.iteye.com/upload/attachment/0123/7520/76ff9288-0d1c-3e46-ae29-ce59e4a48ea2.png[/img]
<think>好的,我现在需要分析JDK8中的AbstractQueue类的源码。首先,我应该先了解AbstractQueueJava集合框架中的位置和作用。根据之前的知识,AbstractQueue是一个抽象类,它实现了Queue接口,提供了队列操作的基本实现。用户通常通过继承这个类来创建具体的队列实现,比如PriorityQueue或者ConcurrentLinkedQueue。 接下来,我需要找到JDK8的源码。可以通过OpenJDK的代码库或者下载JDK8的源码包来查看。AbstractQueue类位于java.util包中。打开源码文件后,首先看一下类的声明: public abstract class AbstractQueue<E> extends AbstractCollection<E> implements Queue<E> { 这说明它继承自AbstractCollection,并实现了Queue接口。接下来,查看构造方法,AbstractQueue只有一个无参构造方法,这是合理的,因为作为抽象类,它不需要直接实例化。 然后,重点放在核心方法上。Queue接口定义了add、offer、remove、poll、element、peek等方法。AbstractQueue可能提供了这些方法的部分实现。 比如,add方法通常调用offer方法,如果offer返回false则抛出异常。查看源码: public boolean add(E e) { if (offer(e)) return true; else throw new IllegalStateException("Queue full"); } 这说明add依赖于offer的具体实现,如果子类没有重写offer,可能会导致问题。这符合模板方法模式,抽象类定义结构,具体实现由子类完成。 接下来是remove方法: public E remove() { E x = poll(); if (x != null) return x; else throw new NoSuchElementException(); } 同样,remove调用了poll,如果poll返回null则抛出异常。这里需要注意线程安全的问题,因为AbstractQueue本身并没有同步机制,子类需要自行处理并发情况。 然后是element方法: public E element() { E x = peek(); if (x != null) return x; else throw new NoSuchElementException(); } 同样依赖peek的实现。AbstractQueue的这些方法通过调用子类实现的offer、poll、peek来完成功能,如果子类没有正确实现,可能会抛出异常。 接下来需要查看是否有其他方法,比如addAll。在AbstractQueue中,addAll方法被重写: 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; } 这里遍历集合c,逐个调用add方法。如果添加任何一个元素失败(比如队列容量限制),会抛出IllegalStateException。需要注意的是,如果中途出现异常,前面的元素已经添加成功,但后面的不会继续,这可能导致部分添加的情况。 接下来分析AbstractQueue的代码是否存在依赖或反射调用,但根据引用[1],静态分析工具如jdeps可能无法检测到反射调用的内部API。不过查看AbstractQueue的源码,它主要依赖于标准集合框架的方法,没有明显的反射使用,因此jdeps应该可以正确分析其依赖。 此外,关于版本兼容性问题,如引用[2]提到的,如果代码是在JDK8编译的,那么在更高版本的Java上运行不会有问题,但反之则可能抛出UnsupportedClassVersionError。因此分析JDK8的AbstractQueue时,应确保使用JDK8的环境。 最后,参考引用[3],如果有需要构建或测试相关代码,可以参考官方文档,但AbstractQueue作为标准库的一部分,通常不需要单独构建。 总结,AbstractQueue提供了队列操作的基本骨架,子类需要实现关键方法如offer、poll、peek等。它的设计遵循了模板方法模式,减少了重复代码,同时确保了队列操作的一致性。</think>### Java AbstractQueue 源码分析(JDK 8) #### 1. 类定义与继承关系 `AbstractQueue` 是 `java.util` 包中的抽象类,继承自 `AbstractCollection` 并实现了 `Queue` 接口: ```java public abstract class AbstractQueue<E> extends AbstractCollection<E> implements Queue<E> { ``` 它提供了队列操作的骨架实现,子类需实现核心方法如 `offer`、`poll`、`peek` 等[^1]。 --- #### 2. 核心方法实现 ##### (1) `add(E e)` ```java public boolean add(E e) { if (offer(e)) return true; else throw new IllegalStateException("Queue full"); } ``` - **作用**:向队列添加元素,依赖子类实现的 `offer` 方法。 - **异常**:若队列已满(`offer` 返回 `false`),抛出 `IllegalStateException`。 ##### (2) `remove()` ```java public E remove() { E x = poll(); if (x != null) return x; else throw new NoSuchElementException(); } ``` - **作用**:移除并返回队列头部元素,依赖子类的 `poll` 方法。 - **异常**:若队列为空(`poll` 返回 `null`),抛出 `NoSuchElementException`。 ##### (3) `element()` ```java public E element() { E x = peek(); if (x != null) return x; else throw new NoSuchElementException(); } ``` - **作用**:查看队列头部元素,依赖子类的 `peek` 方法。 - **异常**:若队列为空(`peek` 返回 `null`),抛出 `NoSuchElementException`。 ##### (4) `addAll(Collection<? extends E> c)` ```java 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; } ``` - **作用**:批量添加元素,循环调用 `add` 方法。 - **部分添加风险**:若中途抛出异常,已添加的元素会保留在队列中。 --- #### 3. 设计模式与关键点 - **模板方法模式**:`add`、`remove` 等方法通过调用子类实现的 `offer`、`poll` 完成功能。 - **线程安全性**:`AbstractQueue` 未内置同步机制,子类需自行处理并发(如 `ConcurrentLinkedQueue`)。 - **异常策略**:强制调用者处理队列空/满的边界条件。 --- #### 4. 典型子类示例 - **`PriorityQueue`**:基于堆结构的优先级队列。 - **`ConcurrentLinkedQueue`**:线程安全的无界非阻塞队列。 --- §§ 相关问题 §§ 1. `AbstractQueue` 的 `addAll` 方法在部分添加失败时如何处理? 2. 如何基于 `AbstractQueue` 实现一个线程安全的队列? 3. 为什么 `AbstractQueue` 要求子类必须实现 `offer` 方法? [^1]: 引用自 JDK 8 源码 `AbstractQueue.java`。 [^2]: 关于 Java 版本兼容性问题的说明。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值