JDK1.8源码笔记(11) Collection&AbstractCollection

Collection

前言

The root interface in the <i>collection hierarchy</i>.
collection hierarchy的根。

A collection represents a group of objects, known as its <i>elements</i>.
一个collection就是一组被称为element的对象。

Some collections allow duplicate elements and others do not.
Some are ordered and others unordered.

* The JDK does not provide any <i>direct</i>
* implementations of this interface: it provides implementations of more
* specific subinterfaces like <tt>Set</tt> and <tt>List</tt>.
JDK对于这个接口没有提供任何直接的实现。

This interface is typically used to pass collections around and manipulate them where maximum generality is desired.
这个接口通常用于传递集合,并且通过最普遍的方式操作。

<p><i>Bags</i> or <i>multisets</i> (unordered collections that may contain duplicate elements) should implement this interface directly.
Bags或者multisets这这无序可重复集合应该直接实现这个接口。

* <p>All general-purpose <tt>Collection</tt> implementation classes (which
* typically implement <tt>Collection</tt> indirectly through one of its
* subinterfaces) should provide two "standard" constructors: a void (no
* arguments) constructor, which creates an empty collection, and a
* constructor with a single argument of type <tt>Collection</tt>, which
* creates a new collection with the same elements as its argument.  In
* effect, the latter constructor allows the user to copy any collection,
* producing an equivalent collection of the desired implementation type.
* There is no way to enforce this convention (as interfaces cannot contain
* constructors) but all of the general-purpose <tt>Collection</tt>
* implementations in the Java platform libraries comply.
如果你实现了一个Collection,起码应该有两个构造方法,一个是无参数的,一个是有一个参数但是是自己本身类型的,以便用户能够通过这个构造方法进行Collection的复制。

* <p>The "destructive" methods contained in this interface, that is, the
* methods that modify the collection on which they operate, are specified to
* throw <tt>UnsupportedOperationException</tt> if this collection does not
* support the operation.  If this is the case, these methods may, but are not
* required to, throw an <tt>UnsupportedOperationException</tt> if the
* invocation would have no effect on the collection.  For example, invoking
* the {@link #addAll(Collection)} method on an unmodifiable collection may,
* but is not required to, throw the exception if the collection to be added
* is empty.
这个接口是有一些“destructive”方法的,这些方法就是如果你在一个集合上使用不支持的操作,就会抛出UnsupportedOperationException异常。

Some collection implementations have restrictions on the elements that they may contain.
有些集合的实现可能会对能包含的element有限制。

For example, some implementations prohibit null elements, and some have restrictions on the types of their elements.
比如有些禁止null值,有些限制element的类型。

* Attempting to
* add an ineligible element throws an unchecked exception, typically
* <tt>NullPointerException</tt> or <tt>ClassCastException</tt>.
尝试添加非法element会抛出uncheck异常。

* Attempting
* to query the presence of an ineligible element may throw an exception,
* or it may simply return false; some implementations will exhibit the former
* behavior and some will exhibit the latter.
尝试查询非法element可能会抛出异常,也可能返回false。

It is up to each collection to determine its own synchronization policy.
由每个collection决定自己的同步策略。

Many methods in Collections Framework interfaces are defined in terms of the {@link Object#equals(Object) equals} method.
好多方法都是以equals为依据来定义的。

* For example,
* the specification for the {@link #contains(Object) contains(Object o)}
* method says: "returns <tt>true</tt> if and only if this collection
* contains at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>."
比如说,contains方法,返回为真当且仅当集合中至少包含一个element和o符合o==null ? e==null : o.equals(e)。

* <p>Some collection operations which perform recursive traversal of the
* collection may fail with an exception for self-referential instances where
* the collection directly or indirectly contains itself.
有些collection操作递归地便利容器会导致self-referential异常。

* The default method implementations (inherited or otherwise) do not apply any
* synchronization protocol.
方法的默认实现并不适用于任何同步规则。

* If a {@code Collection} implementation has a
* specific synchronization protocol, then it must override default
* implementations to apply that protocol.
如果一个容器的实现有一个具体的同步协议,那必须重写默认方法去实现协议。

继承类&实现接口

实现Iterable接口,该接口我们在前面已经分析过。

成员变量&成员方法

int size();
返回collection中element的数量,如果超过了Integer.MAX_VALUE,则返回Integer.MAX_VALUE。

boolean isEmpty();
判断是否有element。

boolean contains(Object o);
* Returns <tt>true</tt> if this collection contains the specified element.
* More formally, returns <tt>true</tt> if and only if this collection
* contains at least one element <tt>e</tt> such that
* <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
当且仅当至少有一个element满足o==null ? e==null : o.equals(e)时返回true。

Iterator<E> iterator();
* Returns an iterator over the elements in this collection.  There are no
* guarantees concerning the order in which the elements are returned
* (unless this collection is an instance of some class that provides a
* guarantee).
返回一个collection中所有element上的iterator。不能保证element的顺序。
除非collection能提供保证。

Object[] toArray();
* Returns an array containing all of the elements in this collection.
* If this collection makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the elements in
* the same order.
返回一个包含所有element的数组。如果collection在iterator返回数据的时候有一定的保障,那么这个数组也应该是相同顺序的。
* <p>The returned array will be "safe" in that no references to it are
* maintained by this collection.  (In other words, this method must
* allocate a new array even if this collection is backed by an array).
* The caller is thus free to modify the returned array.
应该返回一个和collection内部不管的全新数组。
* <p>This method acts as bridge between array-based and collection-based
* APIs.
这是一个起到了沟通array-based和collection-based的api。

<T> T[] toArray(T[] a);
首先要注意到,这个是T,而Collection声明的时候用得是E,可以不一样,说明可以转成其他类型。
* Returns an array containing all of the elements in this collection;
* the runtime type of the returned array is that of the specified array.
* If the collection fits in the specified array, it is returned therein.
* Otherwise, a new array is allocated with the runtime type of the
* specified array and the size of this collection.
返回一个含有该collection内所有element的数组。
返回的数组的runtime type是由传入的数组指定的。
如果collection适合放在这个数组里,那会用它返回,否则会分配一个新的runtime type数组并且大小等于collection。
* <p>Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs.  Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.
和刚刚介绍的toArray方法相同,这个方法也可以作为array-based和collection-based的桥梁api。更重要的是,这个方法允许对输出数组的类型进行控制,在特定情况下,还可以节省空间。

boolean add(E e);
* Ensures that this collection contains the specified element (optional
* operation).  Returns <tt>true</tt> if this collection changed as a
* result of the call.  (Returns <tt>false</tt> if this collection does
* not permit duplicates and already contains the specified element.)<p>
确保collection还有具体的element(可选操作)。如果collection发生了改变,返回true。返回false如果collection如果已经含有这个element并且collection还不允许重复。
* Collections that support this operation may place limitations on what
* elements may be added to this collection.  In particular, some
* collections will refuse to add <tt>null</tt> elements, and others will
* impose restrictions on the type of elements that may be added.
* Collection classes should clearly specify in their documentation any
* restrictions on what elements may be added.<p>
Collections可能会限制插入的类型。有些可能不允许插入null,或者严格限定具体的type。
* If a collection refuses to add a particular element for any reason
* other than that it already contains the element, it <i>must</i> throw
* an exception (rather than returning <tt>false</tt>).  This preserves
* the invariant that a collection always contains the specified element
* after this call returns.
如果一个collection拒绝添加一个element因为重复以外的原因,那么必须以抛出异常的形式表示,而不是返回false。

boolean remove(Object o);
* Removes a single instance of the specified element from this
* collection, if it is present (optional operation).  More formally,
* removes an element <tt>e</tt> such that
* <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, if
* this collection contains one or more such elements.  Returns
* <tt>true</tt> if this collection contained the specified element (or
* equivalently, if this collection changed as a result of the call).
移除掉符合contains条件的所有element,如果collection被修改,返回true。

boolean containsAll(Collection<?> c);
* Returns <tt>true</tt> if this collection contains all of the elements
* in the specified collection.
集合包含判断。

boolean addAll(Collection<? extends E> c);
* Adds all of the elements in the specified collection to this collection
* (optional operation).

boolean removeAll(Collection<?> c);
* Removes all of this collection's elements that are also contained in the
* specified collection (optional operation).

boolean retainAll(Collection<?> c);
* Retains only the elements in this collection that are contained in the
* specified collection (optional operation).
取补集。

void clear();
* Removes all of the elements from this collection (optional operation).
* The collection will be empty after this method returns.
清空collection。

boolean equals(Object o);
* Compares the specified object with this collection for equality. <p>
*
* While the <tt>Collection</tt> interface adds no stipulations to the
* general contract for the <tt>Object.equals</tt>, programmers who
* implement the <tt>Collection</tt> interface "directly" (in other words,
* create a class that is a <tt>Collection</tt> but is not a <tt>Set</tt>
* or a <tt>List</tt>) must exercise care if they choose to override the
* <tt>Object.equals</tt>.  It is not necessary to do so, and the simplest
* course of action is to rely on <tt>Object</tt>'s implementation, but
* the implementor may wish to implement a "value comparison" in place of
* the default "reference comparison."  (The <tt>List</tt> and
* <tt>Set</tt> interfaces mandate such value comparisons.)<p>

int hashCode();
* Returns the hash code value for this collection.  While the
* <tt>Collection</tt> interface adds no stipulations to the general
* contract for the <tt>Object.hashCode</tt> method, programmers should
* take note that any class that overrides the <tt>Object.equals</tt>
* method must also override the <tt>Object.hashCode</tt> method in order
* to satisfy the general contract for the <tt>Object.hashCode</tt> method.
* In particular, <tt>c1.equals(c2)</tt> implies that
* <tt>c1.hashCode()==c2.hashCode()</tt>.
返回这个collection本身的hash code。程序员需要注意重写Object.equals都应该同样重写Object.hashCode。

AbstractCollection

前言

* This class provides a skeletal implementation of the <tt>Collection</tt>
* interface, to minimize the effort required to implement this interface. <p>
Collection是一个接口,而在JDK1.8之前,在接口内是不能通过default关键字包含函数体的。所以有一些Collection的公有实现,可以写一个抽象类去实现Collection。

成员变量&成员方法

public boolean isEmpty() {
    return size() == 0;
}

public boolean contains(Object o) {
    Iterator<E> it = iterator();
    if (o==null) {
        while (it.hasNext())
            if (it.next()==null)
                return true;
    } else {
        while (it.hasNext())
            if (o.equals(it.next()))
                return true;
    }
    return false;
}

用迭代器进行判断。

public void clear() {
    Iterator<E> it = iterator();
    while (it.hasNext()) {
        it.next();
        it.remove();
    }
}

用迭代器进行清空。

public String toString() {
    Iterator<E> it = iterator();
    if (! it.hasNext())
        return "[]";

    StringBuilder sb = new StringBuilder();
    sb.append('[');
    for (;;) {
        E e = it.next();
        sb.append(e == this ? "(this Collection)" : e);
        if (! it.hasNext())
            return sb.append(']').toString();
        sb.append(',').append(' ');
    }
}

到底怎么才能做到e == this?请看下例:
List<Collection> list = new ArrayList<>();
list.add(list);
System.out.println(list);

public boolean remove(Object o) {
    Iterator<E> it = iterator();
    if (o==null) {
        while (it.hasNext()) {
            if (it.next()==null) {
                it.remove();
                return true;
            }
        }
    } else {
        while (it.hasNext()) {
            if (o.equals(it.next())) {
                it.remove();
                return true;
            }
        }
    }
    return false;
}

只移除一个,就是第一个找到的。

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值