Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/util/Collection.java
38829 views
/*1* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.util;2627import java.util.function.Predicate;28import java.util.stream.Stream;29import java.util.stream.StreamSupport;3031/**32* The root interface in the <i>collection hierarchy</i>. A collection33* represents a group of objects, known as its <i>elements</i>. Some34* collections allow duplicate elements and others do not. Some are ordered35* and others unordered. The JDK does not provide any <i>direct</i>36* implementations of this interface: it provides implementations of more37* specific subinterfaces like <tt>Set</tt> and <tt>List</tt>. This interface38* is typically used to pass collections around and manipulate them where39* maximum generality is desired.40*41* <p><i>Bags</i> or <i>multisets</i> (unordered collections that may contain42* duplicate elements) should implement this interface directly.43*44* <p>All general-purpose <tt>Collection</tt> implementation classes (which45* typically implement <tt>Collection</tt> indirectly through one of its46* subinterfaces) should provide two "standard" constructors: a void (no47* arguments) constructor, which creates an empty collection, and a48* constructor with a single argument of type <tt>Collection</tt>, which49* creates a new collection with the same elements as its argument. In50* effect, the latter constructor allows the user to copy any collection,51* producing an equivalent collection of the desired implementation type.52* There is no way to enforce this convention (as interfaces cannot contain53* constructors) but all of the general-purpose <tt>Collection</tt>54* implementations in the Java platform libraries comply.55*56* <p>The "destructive" methods contained in this interface, that is, the57* methods that modify the collection on which they operate, are specified to58* throw <tt>UnsupportedOperationException</tt> if this collection does not59* support the operation. If this is the case, these methods may, but are not60* required to, throw an <tt>UnsupportedOperationException</tt> if the61* invocation would have no effect on the collection. For example, invoking62* the {@link #addAll(Collection)} method on an unmodifiable collection may,63* but is not required to, throw the exception if the collection to be added64* is empty.65*66* <p><a name="optional-restrictions">67* Some collection implementations have restrictions on the elements that68* they may contain.</a> For example, some implementations prohibit null elements,69* and some have restrictions on the types of their elements. Attempting to70* add an ineligible element throws an unchecked exception, typically71* <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting72* to query the presence of an ineligible element may throw an exception,73* or it may simply return false; some implementations will exhibit the former74* behavior and some will exhibit the latter. More generally, attempting an75* operation on an ineligible element whose completion would not result in76* the insertion of an ineligible element into the collection may throw an77* exception or it may succeed, at the option of the implementation.78* Such exceptions are marked as "optional" in the specification for this79* interface.80*81* <p>It is up to each collection to determine its own synchronization82* policy. In the absence of a stronger guarantee by the83* implementation, undefined behavior may result from the invocation84* of any method on a collection that is being mutated by another85* thread; this includes direct invocations, passing the collection to86* a method that might perform invocations, and using an existing87* iterator to examine the collection.88*89* <p>Many methods in Collections Framework interfaces are defined in90* terms of the {@link Object#equals(Object) equals} method. For example,91* the specification for the {@link #contains(Object) contains(Object o)}92* method says: "returns <tt>true</tt> if and only if this collection93* contains at least one element <tt>e</tt> such that94* <tt>(o==null ? e==null : o.equals(e))</tt>." This specification should95* <i>not</i> be construed to imply that invoking <tt>Collection.contains</tt>96* with a non-null argument <tt>o</tt> will cause <tt>o.equals(e)</tt> to be97* invoked for any element <tt>e</tt>. Implementations are free to implement98* optimizations whereby the <tt>equals</tt> invocation is avoided, for99* example, by first comparing the hash codes of the two elements. (The100* {@link Object#hashCode()} specification guarantees that two objects with101* unequal hash codes cannot be equal.) More generally, implementations of102* the various Collections Framework interfaces are free to take advantage of103* the specified behavior of underlying {@link Object} methods wherever the104* implementor deems it appropriate.105*106* <p>Some collection operations which perform recursive traversal of the107* collection may fail with an exception for self-referential instances where108* the collection directly or indirectly contains itself. This includes the109* {@code clone()}, {@code equals()}, {@code hashCode()} and {@code toString()}110* methods. Implementations may optionally handle the self-referential scenario,111* however most current implementations do not do so.112*113* <p>This interface is a member of the114* <a href="{@docRoot}/../technotes/guides/collections/index.html">115* Java Collections Framework</a>.116*117* @implSpec118* The default method implementations (inherited or otherwise) do not apply any119* synchronization protocol. If a {@code Collection} implementation has a120* specific synchronization protocol, then it must override default121* implementations to apply that protocol.122*123* @param <E> the type of elements in this collection124*125* @author Josh Bloch126* @author Neal Gafter127* @see Set128* @see List129* @see Map130* @see SortedSet131* @see SortedMap132* @see HashSet133* @see TreeSet134* @see ArrayList135* @see LinkedList136* @see Vector137* @see Collections138* @see Arrays139* @see AbstractCollection140* @since 1.2141*/142143public interface Collection<E> extends Iterable<E> {144// Query Operations145146/**147* Returns the number of elements in this collection. If this collection148* contains more than <tt>Integer.MAX_VALUE</tt> elements, returns149* <tt>Integer.MAX_VALUE</tt>.150*151* @return the number of elements in this collection152*/153int size();154155/**156* Returns <tt>true</tt> if this collection contains no elements.157*158* @return <tt>true</tt> if this collection contains no elements159*/160boolean isEmpty();161162/**163* Returns <tt>true</tt> if this collection contains the specified element.164* More formally, returns <tt>true</tt> if and only if this collection165* contains at least one element <tt>e</tt> such that166* <tt>(o==null ? e==null : o.equals(e))</tt>.167*168* @param o element whose presence in this collection is to be tested169* @return <tt>true</tt> if this collection contains the specified170* element171* @throws ClassCastException if the type of the specified element172* is incompatible with this collection173* (<a href="#optional-restrictions">optional</a>)174* @throws NullPointerException if the specified element is null and this175* collection does not permit null elements176* (<a href="#optional-restrictions">optional</a>)177*/178boolean contains(Object o);179180/**181* Returns an iterator over the elements in this collection. There are no182* guarantees concerning the order in which the elements are returned183* (unless this collection is an instance of some class that provides a184* guarantee).185*186* @return an <tt>Iterator</tt> over the elements in this collection187*/188Iterator<E> iterator();189190/**191* Returns an array containing all of the elements in this collection.192* If this collection makes any guarantees as to what order its elements193* are returned by its iterator, this method must return the elements in194* the same order.195*196* <p>The returned array will be "safe" in that no references to it are197* maintained by this collection. (In other words, this method must198* allocate a new array even if this collection is backed by an array).199* The caller is thus free to modify the returned array.200*201* <p>This method acts as bridge between array-based and collection-based202* APIs.203*204* @return an array containing all of the elements in this collection205*/206Object[] toArray();207208/**209* Returns an array containing all of the elements in this collection;210* the runtime type of the returned array is that of the specified array.211* If the collection fits in the specified array, it is returned therein.212* Otherwise, a new array is allocated with the runtime type of the213* specified array and the size of this collection.214*215* <p>If this collection fits in the specified array with room to spare216* (i.e., the array has more elements than this collection), the element217* in the array immediately following the end of the collection is set to218* <tt>null</tt>. (This is useful in determining the length of this219* collection <i>only</i> if the caller knows that this collection does220* not contain any <tt>null</tt> elements.)221*222* <p>If this collection makes any guarantees as to what order its elements223* are returned by its iterator, this method must return the elements in224* the same order.225*226* <p>Like the {@link #toArray()} method, this method acts as bridge between227* array-based and collection-based APIs. Further, this method allows228* precise control over the runtime type of the output array, and may,229* under certain circumstances, be used to save allocation costs.230*231* <p>Suppose <tt>x</tt> is a collection known to contain only strings.232* The following code can be used to dump the collection into a newly233* allocated array of <tt>String</tt>:234*235* <pre>236* String[] y = x.toArray(new String[0]);</pre>237*238* Note that <tt>toArray(new Object[0])</tt> is identical in function to239* <tt>toArray()</tt>.240*241* @param <T> the runtime type of the array to contain the collection242* @param a the array into which the elements of this collection are to be243* stored, if it is big enough; otherwise, a new array of the same244* runtime type is allocated for this purpose.245* @return an array containing all of the elements in this collection246* @throws ArrayStoreException if the runtime type of the specified array247* is not a supertype of the runtime type of every element in248* this collection249* @throws NullPointerException if the specified array is null250*/251<T> T[] toArray(T[] a);252253// Modification Operations254255/**256* Ensures that this collection contains the specified element (optional257* operation). Returns <tt>true</tt> if this collection changed as a258* result of the call. (Returns <tt>false</tt> if this collection does259* not permit duplicates and already contains the specified element.)<p>260*261* Collections that support this operation may place limitations on what262* elements may be added to this collection. In particular, some263* collections will refuse to add <tt>null</tt> elements, and others will264* impose restrictions on the type of elements that may be added.265* Collection classes should clearly specify in their documentation any266* restrictions on what elements may be added.<p>267*268* If a collection refuses to add a particular element for any reason269* other than that it already contains the element, it <i>must</i> throw270* an exception (rather than returning <tt>false</tt>). This preserves271* the invariant that a collection always contains the specified element272* after this call returns.273*274* @param e element whose presence in this collection is to be ensured275* @return <tt>true</tt> if this collection changed as a result of the276* call277* @throws UnsupportedOperationException if the <tt>add</tt> operation278* is not supported by this collection279* @throws ClassCastException if the class of the specified element280* prevents it from being added to this collection281* @throws NullPointerException if the specified element is null and this282* collection does not permit null elements283* @throws IllegalArgumentException if some property of the element284* prevents it from being added to this collection285* @throws IllegalStateException if the element cannot be added at this286* time due to insertion restrictions287*/288boolean add(E e);289290/**291* Removes a single instance of the specified element from this292* collection, if it is present (optional operation). More formally,293* removes an element <tt>e</tt> such that294* <tt>(o==null ? e==null : o.equals(e))</tt>, if295* this collection contains one or more such elements. Returns296* <tt>true</tt> if this collection contained the specified element (or297* equivalently, if this collection changed as a result of the call).298*299* @param o element to be removed from this collection, if present300* @return <tt>true</tt> if an element was removed as a result of this call301* @throws ClassCastException if the type of the specified element302* is incompatible with this collection303* (<a href="#optional-restrictions">optional</a>)304* @throws NullPointerException if the specified element is null and this305* collection does not permit null elements306* (<a href="#optional-restrictions">optional</a>)307* @throws UnsupportedOperationException if the <tt>remove</tt> operation308* is not supported by this collection309*/310boolean remove(Object o);311312313// Bulk Operations314315/**316* Returns <tt>true</tt> if this collection contains all of the elements317* in the specified collection.318*319* @param c collection to be checked for containment in this collection320* @return <tt>true</tt> if this collection contains all of the elements321* in the specified collection322* @throws ClassCastException if the types of one or more elements323* in the specified collection are incompatible with this324* collection325* (<a href="#optional-restrictions">optional</a>)326* @throws NullPointerException if the specified collection contains one327* or more null elements and this collection does not permit null328* elements329* (<a href="#optional-restrictions">optional</a>),330* or if the specified collection is null.331* @see #contains(Object)332*/333boolean containsAll(Collection<?> c);334335/**336* Adds all of the elements in the specified collection to this collection337* (optional operation). The behavior of this operation is undefined if338* the specified collection is modified while the operation is in progress.339* (This implies that the behavior of this call is undefined if the340* specified collection is this collection, and this collection is341* nonempty.)342*343* @param c collection containing elements to be added to this collection344* @return <tt>true</tt> if this collection changed as a result of the call345* @throws UnsupportedOperationException if the <tt>addAll</tt> operation346* is not supported by this collection347* @throws ClassCastException if the class of an element of the specified348* collection prevents it from being added to this collection349* @throws NullPointerException if the specified collection contains a350* null element and this collection does not permit null elements,351* or if the specified collection is null352* @throws IllegalArgumentException if some property of an element of the353* specified collection prevents it from being added to this354* collection355* @throws IllegalStateException if not all the elements can be added at356* this time due to insertion restrictions357* @see #add(Object)358*/359boolean addAll(Collection<? extends E> c);360361/**362* Removes all of this collection's elements that are also contained in the363* specified collection (optional operation). After this call returns,364* this collection will contain no elements in common with the specified365* collection.366*367* @param c collection containing elements to be removed from this collection368* @return <tt>true</tt> if this collection changed as a result of the369* call370* @throws UnsupportedOperationException if the <tt>removeAll</tt> method371* is not supported by this collection372* @throws ClassCastException if the types of one or more elements373* in this collection are incompatible with the specified374* collection375* (<a href="#optional-restrictions">optional</a>)376* @throws NullPointerException if this collection contains one or more377* null elements and the specified collection does not support378* null elements379* (<a href="#optional-restrictions">optional</a>),380* or if the specified collection is null381* @see #remove(Object)382* @see #contains(Object)383*/384boolean removeAll(Collection<?> c);385386/**387* Removes all of the elements of this collection that satisfy the given388* predicate. Errors or runtime exceptions thrown during iteration or by389* the predicate are relayed to the caller.390*391* @implSpec392* The default implementation traverses all elements of the collection using393* its {@link #iterator}. Each matching element is removed using394* {@link Iterator#remove()}. If the collection's iterator does not395* support removal then an {@code UnsupportedOperationException} will be396* thrown on the first matching element.397*398* @param filter a predicate which returns {@code true} for elements to be399* removed400* @return {@code true} if any elements were removed401* @throws NullPointerException if the specified filter is null402* @throws UnsupportedOperationException if elements cannot be removed403* from this collection. Implementations may throw this exception if a404* matching element cannot be removed or if, in general, removal is not405* supported.406* @since 1.8407*/408default boolean removeIf(Predicate<? super E> filter) {409Objects.requireNonNull(filter);410boolean removed = false;411final Iterator<E> each = iterator();412while (each.hasNext()) {413if (filter.test(each.next())) {414each.remove();415removed = true;416}417}418return removed;419}420421/**422* Retains only the elements in this collection that are contained in the423* specified collection (optional operation). In other words, removes from424* this collection all of its elements that are not contained in the425* specified collection.426*427* @param c collection containing elements to be retained in this collection428* @return <tt>true</tt> if this collection changed as a result of the call429* @throws UnsupportedOperationException if the <tt>retainAll</tt> operation430* is not supported by this collection431* @throws ClassCastException if the types of one or more elements432* in this collection are incompatible with the specified433* collection434* (<a href="#optional-restrictions">optional</a>)435* @throws NullPointerException if this collection contains one or more436* null elements and the specified collection does not permit null437* elements438* (<a href="#optional-restrictions">optional</a>),439* or if the specified collection is null440* @see #remove(Object)441* @see #contains(Object)442*/443boolean retainAll(Collection<?> c);444445/**446* Removes all of the elements from this collection (optional operation).447* The collection will be empty after this method returns.448*449* @throws UnsupportedOperationException if the <tt>clear</tt> operation450* is not supported by this collection451*/452void clear();453454455// Comparison and hashing456457/**458* Compares the specified object with this collection for equality. <p>459*460* While the <tt>Collection</tt> interface adds no stipulations to the461* general contract for the <tt>Object.equals</tt>, programmers who462* implement the <tt>Collection</tt> interface "directly" (in other words,463* create a class that is a <tt>Collection</tt> but is not a <tt>Set</tt>464* or a <tt>List</tt>) must exercise care if they choose to override the465* <tt>Object.equals</tt>. It is not necessary to do so, and the simplest466* course of action is to rely on <tt>Object</tt>'s implementation, but467* the implementor may wish to implement a "value comparison" in place of468* the default "reference comparison." (The <tt>List</tt> and469* <tt>Set</tt> interfaces mandate such value comparisons.)<p>470*471* The general contract for the <tt>Object.equals</tt> method states that472* equals must be symmetric (in other words, <tt>a.equals(b)</tt> if and473* only if <tt>b.equals(a)</tt>). The contracts for <tt>List.equals</tt>474* and <tt>Set.equals</tt> state that lists are only equal to other lists,475* and sets to other sets. Thus, a custom <tt>equals</tt> method for a476* collection class that implements neither the <tt>List</tt> nor477* <tt>Set</tt> interface must return <tt>false</tt> when this collection478* is compared to any list or set. (By the same logic, it is not possible479* to write a class that correctly implements both the <tt>Set</tt> and480* <tt>List</tt> interfaces.)481*482* @param o object to be compared for equality with this collection483* @return <tt>true</tt> if the specified object is equal to this484* collection485*486* @see Object#equals(Object)487* @see Set#equals(Object)488* @see List#equals(Object)489*/490boolean equals(Object o);491492/**493* Returns the hash code value for this collection. While the494* <tt>Collection</tt> interface adds no stipulations to the general495* contract for the <tt>Object.hashCode</tt> method, programmers should496* take note that any class that overrides the <tt>Object.equals</tt>497* method must also override the <tt>Object.hashCode</tt> method in order498* to satisfy the general contract for the <tt>Object.hashCode</tt> method.499* In particular, <tt>c1.equals(c2)</tt> implies that500* <tt>c1.hashCode()==c2.hashCode()</tt>.501*502* @return the hash code value for this collection503*504* @see Object#hashCode()505* @see Object#equals(Object)506*/507int hashCode();508509/**510* Creates a {@link Spliterator} over the elements in this collection.511*512* Implementations should document characteristic values reported by the513* spliterator. Such characteristic values are not required to be reported514* if the spliterator reports {@link Spliterator#SIZED} and this collection515* contains no elements.516*517* <p>The default implementation should be overridden by subclasses that518* can return a more efficient spliterator. In order to519* preserve expected laziness behavior for the {@link #stream()} and520* {@link #parallelStream()}} methods, spliterators should either have the521* characteristic of {@code IMMUTABLE} or {@code CONCURRENT}, or be522* <em><a href="Spliterator.html#binding">late-binding</a></em>.523* If none of these is practical, the overriding class should describe the524* spliterator's documented policy of binding and structural interference,525* and should override the {@link #stream()} and {@link #parallelStream()}526* methods to create streams using a {@code Supplier} of the spliterator,527* as in:528* <pre>{@code529* Stream<E> s = StreamSupport.stream(() -> spliterator(), spliteratorCharacteristics)530* }</pre>531* <p>These requirements ensure that streams produced by the532* {@link #stream()} and {@link #parallelStream()} methods will reflect the533* contents of the collection as of initiation of the terminal stream534* operation.535*536* @implSpec537* The default implementation creates a538* <em><a href="Spliterator.html#binding">late-binding</a></em> spliterator539* from the collections's {@code Iterator}. The spliterator inherits the540* <em>fail-fast</em> properties of the collection's iterator.541* <p>542* The created {@code Spliterator} reports {@link Spliterator#SIZED}.543*544* @implNote545* The created {@code Spliterator} additionally reports546* {@link Spliterator#SUBSIZED}.547*548* <p>If a spliterator covers no elements then the reporting of additional549* characteristic values, beyond that of {@code SIZED} and {@code SUBSIZED},550* does not aid clients to control, specialize or simplify computation.551* However, this does enable shared use of an immutable and empty552* spliterator instance (see {@link Spliterators#emptySpliterator()}) for553* empty collections, and enables clients to determine if such a spliterator554* covers no elements.555*556* @return a {@code Spliterator} over the elements in this collection557* @since 1.8558*/559@Override560default Spliterator<E> spliterator() {561return Spliterators.spliterator(this, 0);562}563564/**565* Returns a sequential {@code Stream} with this collection as its source.566*567* <p>This method should be overridden when the {@link #spliterator()}568* method cannot return a spliterator that is {@code IMMUTABLE},569* {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}570* for details.)571*572* @implSpec573* The default implementation creates a sequential {@code Stream} from the574* collection's {@code Spliterator}.575*576* @return a sequential {@code Stream} over the elements in this collection577* @since 1.8578*/579default Stream<E> stream() {580return StreamSupport.stream(spliterator(), false);581}582583/**584* Returns a possibly parallel {@code Stream} with this collection as its585* source. It is allowable for this method to return a sequential stream.586*587* <p>This method should be overridden when the {@link #spliterator()}588* method cannot return a spliterator that is {@code IMMUTABLE},589* {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}590* for details.)591*592* @implSpec593* The default implementation creates a parallel {@code Stream} from the594* collection's {@code Spliterator}.595*596* @return a possibly parallel {@code Stream} over the elements in this597* collection598* @since 1.8599*/600default Stream<E> parallelStream() {601return StreamSupport.stream(spliterator(), true);602}603}604605606