JAVA集合源码攻坚战(18)——AbstractQueue

JAVA集合源码攻坚战(18)——AbstractQueue

前言

今天周一,刚上班,先看看源码,补充下能量!

正文

AbstractQueue的地位

java.util 
Class AbstractQueue<E>

java.lang.Object 
	java.util.AbstractCollection<E> 
		java.util.AbstractQueue<E> 

参数类型 
E - 在此集合中保存的元素的类型 
All Implemented Interfaces: 
Iterable <E>, Collection <E>, Queue <E> 
已知直接子类: 
ArrayBlockingQueue , ConcurrentLinkedQueue , DelayQueue , LinkedBlockingDeque , LinkedBlockingQueue , LinkedTransferQueue , PriorityBlockingQueue , PriorityQueue , SynchronousQueue 

可以看到,AbstractQueue继承了AbstractCollection类,实现了Queue。
AbstractQueue是提供了对Queue的一些操作的骨架实现。
在官方文档中,特别提到了一点

A Queue implementation that extends this class must
minimally define a method {@link Queue#offer} which does not permit
insertion of null 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的实现类,必须最低限度的定义一个不允许插入null元素的offer方法。如果无法满足这些要求,请考虑使用AbstractCollection。

构造方法

/**
     * 供子类使用的构造器
     * Constructor for use by subclasses.
     */
    protected AbstractQueue() {
    }

数据操作方法

1、添加操作

	public boolean add(E e) {
        // 依赖于Queue接口中的offer方法
        if (offer(e))
            return true;
        else
            throw new IllegalStateException("Queue full");
    }

2、移除操作

    public E remove() {
        // 实际调用Queue中的poll方法
        E x = poll();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

3、获取操作

    public E element() {
        // 实际调用Queue的peek方法
        E x = peek();
        if (x != null)
            return x;
        else
            throw new NoSuchElementException();
    }

4、清空操作

    public void clear() {
        // 循环调用poll方法,直到poll方法返回null,表示队列为空
        while (poll() != null)
            ;
    }

5、批量添加操作

    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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值