Collection.java revision 5c35c7ebda68cc39b6bdee20f678a150336ebd1d
1/*
2 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.util;
27
28import java.util.function.Predicate;
29
30/**
31 * The root interface in the <i>collection hierarchy</i>.  A collection
32 * represents a group of objects, known as its <i>elements</i>.  Some
33 * collections allow duplicate elements and others do not.  Some are ordered
34 * and others unordered.  The JDK does not provide any <i>direct</i>
35 * implementations of this interface: it provides implementations of more
36 * specific subinterfaces like <tt>Set</tt> and <tt>List</tt>.  This interface
37 * is typically used to pass collections around and manipulate them where
38 * maximum generality is desired.
39 *
40 * <p><i>Bags</i> or <i>multisets</i> (unordered collections that may contain
41 * duplicate elements) should implement this interface directly.
42 *
43 * <p>All general-purpose <tt>Collection</tt> implementation classes (which
44 * typically implement <tt>Collection</tt> indirectly through one of its
45 * subinterfaces) should provide two "standard" constructors: a void (no
46 * arguments) constructor, which creates an empty collection, and a
47 * constructor with a single argument of type <tt>Collection</tt>, which
48 * creates a new collection with the same elements as its argument.  In
49 * effect, the latter constructor allows the user to copy any collection,
50 * producing an equivalent collection of the desired implementation type.
51 * There is no way to enforce this convention (as interfaces cannot contain
52 * constructors) but all of the general-purpose <tt>Collection</tt>
53 * implementations in the Java platform libraries comply.
54 *
55 * <p>The "destructive" methods contained in this interface, that is, the
56 * methods that modify the collection on which they operate, are specified to
57 * throw <tt>UnsupportedOperationException</tt> if this collection does not
58 * support the operation.  If this is the case, these methods may, but are not
59 * required to, throw an <tt>UnsupportedOperationException</tt> if the
60 * invocation would have no effect on the collection.  For example, invoking
61 * the {@link #addAll(Collection)} method on an unmodifiable collection may,
62 * but is not required to, throw the exception if the collection to be added
63 * is empty.
64 *
65 * <p><a name="optional-restrictions">
66 * Some collection implementations have restrictions on the elements that
67 * they may contain.</a>  For example, some implementations prohibit null elements,
68 * and some have restrictions on the types of their elements.  Attempting to
69 * add an ineligible element throws an unchecked exception, typically
70 * <tt>NullPointerException</tt> or <tt>ClassCastException</tt>.  Attempting
71 * to query the presence of an ineligible element may throw an exception,
72 * or it may simply return false; some implementations will exhibit the former
73 * behavior and some will exhibit the latter.  More generally, attempting an
74 * operation on an ineligible element whose completion would not result in
75 * the insertion of an ineligible element into the collection may throw an
76 * exception or it may succeed, at the option of the implementation.
77 * Such exceptions are marked as "optional" in the specification for this
78 * interface.
79 *
80 * <p>It is up to each collection to determine its own synchronization
81 * policy.  In the absence of a stronger guarantee by the
82 * implementation, undefined behavior may result from the invocation
83 * of any method on a collection that is being mutated by another
84 * thread; this includes direct invocations, passing the collection to
85 * a method that might perform invocations, and using an existing
86 * iterator to examine the collection.
87 *
88 * <p>Many methods in Collections Framework interfaces are defined in
89 * terms of the {@link Object#equals(Object) equals} method.  For example,
90 * the specification for the {@link #contains(Object) contains(Object o)}
91 * method says: "returns <tt>true</tt> if and only if this collection
92 * contains at least one element <tt>e</tt> such that
93 * <tt>(o==null ? e==null : o.equals(e))</tt>."  This specification should
94 * <i>not</i> be construed to imply that invoking <tt>Collection.contains</tt>
95 * with a non-null argument <tt>o</tt> will cause <tt>o.equals(e)</tt> to be
96 * invoked for any element <tt>e</tt>.  Implementations are free to implement
97 * optimizations whereby the <tt>equals</tt> invocation is avoided, for
98 * example, by first comparing the hash codes of the two elements.  (The
99 * {@link Object#hashCode()} specification guarantees that two objects with
100 * unequal hash codes cannot be equal.)  More generally, implementations of
101 * the various Collections Framework interfaces are free to take advantage of
102 * the specified behavior of underlying {@link Object} methods wherever the
103 * implementor deems it appropriate.
104 *
105 * <p>This interface is a member of the
106 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
107 * Java Collections Framework</a>.
108 *
109 * @param <E> the type of elements in this collection
110 *
111 * @author  Josh Bloch
112 * @author  Neal Gafter
113 * @see     Set
114 * @see     List
115 * @see     Map
116 * @see     SortedSet
117 * @see     SortedMap
118 * @see     HashSet
119 * @see     TreeSet
120 * @see     ArrayList
121 * @see     LinkedList
122 * @see     Vector
123 * @see     Collections
124 * @see     Arrays
125 * @see     AbstractCollection
126 * @since 1.2
127 */
128
129public interface Collection<E> extends Iterable<E> {
130    // Query Operations
131
132    /**
133     * Returns the number of elements in this collection.  If this collection
134     * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
135     * <tt>Integer.MAX_VALUE</tt>.
136     *
137     * @return the number of elements in this collection
138     */
139    int size();
140
141    /**
142     * Returns <tt>true</tt> if this collection contains no elements.
143     *
144     * @return <tt>true</tt> if this collection contains no elements
145     */
146    boolean isEmpty();
147
148    /**
149     * Returns <tt>true</tt> if this collection contains the specified element.
150     * More formally, returns <tt>true</tt> if and only if this collection
151     * contains at least one element <tt>e</tt> such that
152     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
153     *
154     * @param o element whose presence in this collection is to be tested
155     * @return <tt>true</tt> if this collection contains the specified
156     *         element
157     * @throws ClassCastException if the type of the specified element
158     *         is incompatible with this collection
159     *         (<a href="#optional-restrictions">optional</a>)
160     * @throws NullPointerException if the specified element is null and this
161     *         collection does not permit null elements
162     *         (<a href="#optional-restrictions">optional</a>)
163     */
164    boolean contains(Object o);
165
166    /**
167     * Returns an iterator over the elements in this collection.  There are no
168     * guarantees concerning the order in which the elements are returned
169     * (unless this collection is an instance of some class that provides a
170     * guarantee).
171     *
172     * @return an <tt>Iterator</tt> over the elements in this collection
173     */
174    Iterator<E> iterator();
175
176    /**
177     * Returns an array containing all of the elements in this collection.
178     * If this collection makes any guarantees as to what order its elements
179     * are returned by its iterator, this method must return the elements in
180     * the same order.
181     *
182     * <p>The returned array will be "safe" in that no references to it are
183     * maintained by this collection.  (In other words, this method must
184     * allocate a new array even if this collection is backed by an array).
185     * The caller is thus free to modify the returned array.
186     *
187     * <p>This method acts as bridge between array-based and collection-based
188     * APIs.
189     *
190     * @return an array containing all of the elements in this collection
191     */
192    Object[] toArray();
193
194    /**
195     * Returns an array containing all of the elements in this collection;
196     * the runtime type of the returned array is that of the specified array.
197     * If the collection fits in the specified array, it is returned therein.
198     * Otherwise, a new array is allocated with the runtime type of the
199     * specified array and the size of this collection.
200     *
201     * <p>If this collection fits in the specified array with room to spare
202     * (i.e., the array has more elements than this collection), the element
203     * in the array immediately following the end of the collection is set to
204     * <tt>null</tt>.  (This is useful in determining the length of this
205     * collection <i>only</i> if the caller knows that this collection does
206     * not contain any <tt>null</tt> elements.)
207     *
208     * <p>If this collection makes any guarantees as to what order its elements
209     * are returned by its iterator, this method must return the elements in
210     * the same order.
211     *
212     * <p>Like the {@link #toArray()} method, this method acts as bridge between
213     * array-based and collection-based APIs.  Further, this method allows
214     * precise control over the runtime type of the output array, and may,
215     * under certain circumstances, be used to save allocation costs.
216     *
217     * <p>Suppose <tt>x</tt> is a collection known to contain only strings.
218     * The following code can be used to dump the collection into a newly
219     * allocated array of <tt>String</tt>:
220     *
221     * <pre>
222     *     String[] y = x.toArray(new String[0]);</pre>
223     *
224     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
225     * <tt>toArray()</tt>.
226     *
227     * @param a the array into which the elements of this collection are to be
228     *        stored, if it is big enough; otherwise, a new array of the same
229     *        runtime type is allocated for this purpose.
230     * @return an array containing all of the elements in this collection
231     * @throws ArrayStoreException if the runtime type of the specified array
232     *         is not a supertype of the runtime type of every element in
233     *         this collection
234     * @throws NullPointerException if the specified array is null
235     */
236    <T> T[] toArray(T[] a);
237
238    // Modification Operations
239
240    /**
241     * Ensures that this collection contains the specified element (optional
242     * operation).  Returns <tt>true</tt> if this collection changed as a
243     * result of the call.  (Returns <tt>false</tt> if this collection does
244     * not permit duplicates and already contains the specified element.)<p>
245     *
246     * Collections that support this operation may place limitations on what
247     * elements may be added to this collection.  In particular, some
248     * collections will refuse to add <tt>null</tt> elements, and others will
249     * impose restrictions on the type of elements that may be added.
250     * Collection classes should clearly specify in their documentation any
251     * restrictions on what elements may be added.<p>
252     *
253     * If a collection refuses to add a particular element for any reason
254     * other than that it already contains the element, it <i>must</i> throw
255     * an exception (rather than returning <tt>false</tt>).  This preserves
256     * the invariant that a collection always contains the specified element
257     * after this call returns.
258     *
259     * @param e element whose presence in this collection is to be ensured
260     * @return <tt>true</tt> if this collection changed as a result of the
261     *         call
262     * @throws UnsupportedOperationException if the <tt>add</tt> operation
263     *         is not supported by this collection
264     * @throws ClassCastException if the class of the specified element
265     *         prevents it from being added to this collection
266     * @throws NullPointerException if the specified element is null and this
267     *         collection does not permit null elements
268     * @throws IllegalArgumentException if some property of the element
269     *         prevents it from being added to this collection
270     * @throws IllegalStateException if the element cannot be added at this
271     *         time due to insertion restrictions
272     */
273    boolean add(E e);
274
275    /**
276     * Removes a single instance of the specified element from this
277     * collection, if it is present (optional operation).  More formally,
278     * removes an element <tt>e</tt> such that
279     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, if
280     * this collection contains one or more such elements.  Returns
281     * <tt>true</tt> if this collection contained the specified element (or
282     * equivalently, if this collection changed as a result of the call).
283     *
284     * @param o element to be removed from this collection, if present
285     * @return <tt>true</tt> if an element was removed as a result of this call
286     * @throws ClassCastException if the type of the specified element
287     *         is incompatible with this collection
288     *         (<a href="#optional-restrictions">optional</a>)
289     * @throws NullPointerException if the specified element is null and this
290     *         collection does not permit null elements
291     *         (<a href="#optional-restrictions">optional</a>)
292     * @throws UnsupportedOperationException if the <tt>remove</tt> operation
293     *         is not supported by this collection
294     */
295    boolean remove(Object o);
296
297
298    // Bulk Operations
299
300    /**
301     * Returns <tt>true</tt> if this collection contains all of the elements
302     * in the specified collection.
303     *
304     * @param  c collection to be checked for containment in this collection
305     * @return <tt>true</tt> if this collection contains all of the elements
306     *         in the specified collection
307     * @throws ClassCastException if the types of one or more elements
308     *         in the specified collection are incompatible with this
309     *         collection
310     *         (<a href="#optional-restrictions">optional</a>)
311     * @throws NullPointerException if the specified collection contains one
312     *         or more null elements and this collection does not permit null
313     *         elements
314     *         (<a href="#optional-restrictions">optional</a>),
315     *         or if the specified collection is null.
316     * @see    #contains(Object)
317     */
318    boolean containsAll(Collection<?> c);
319
320    /**
321     * Adds all of the elements in the specified collection to this collection
322     * (optional operation).  The behavior of this operation is undefined if
323     * the specified collection is modified while the operation is in progress.
324     * (This implies that the behavior of this call is undefined if the
325     * specified collection is this collection, and this collection is
326     * nonempty.)
327     *
328     * @param c collection containing elements to be added to this collection
329     * @return <tt>true</tt> if this collection changed as a result of the call
330     * @throws UnsupportedOperationException if the <tt>addAll</tt> operation
331     *         is not supported by this collection
332     * @throws ClassCastException if the class of an element of the specified
333     *         collection prevents it from being added to this collection
334     * @throws NullPointerException if the specified collection contains a
335     *         null element and this collection does not permit null elements,
336     *         or if the specified collection is null
337     * @throws IllegalArgumentException if some property of an element of the
338     *         specified collection prevents it from being added to this
339     *         collection
340     * @throws IllegalStateException if not all the elements can be added at
341     *         this time due to insertion restrictions
342     * @see #add(Object)
343     */
344    boolean addAll(Collection<? extends E> c);
345
346    /**
347     * Removes all of this collection's elements that are also contained in the
348     * specified collection (optional operation).  After this call returns,
349     * this collection will contain no elements in common with the specified
350     * collection.
351     *
352     * @param c collection containing elements to be removed from this collection
353     * @return <tt>true</tt> if this collection changed as a result of the
354     *         call
355     * @throws UnsupportedOperationException if the <tt>removeAll</tt> method
356     *         is not supported by this collection
357     * @throws ClassCastException if the types of one or more elements
358     *         in this collection are incompatible with the specified
359     *         collection
360     *         (<a href="#optional-restrictions">optional</a>)
361     * @throws NullPointerException if this collection contains one or more
362     *         null elements and the specified collection does not support
363     *         null elements
364     *         (<a href="#optional-restrictions">optional</a>),
365     *         or if the specified collection is null
366     * @see #remove(Object)
367     * @see #contains(Object)
368     */
369    boolean removeAll(Collection<?> c);
370
371
372    /**
373     * Removes all of the elements of this collection that satisfy the given
374     * predicate.  Errors or runtime exceptions thrown during iteration or by
375     * the predicate are relayed to the caller.
376     *
377     * @implSpec
378     * The default implementation traverses all elements of the collection using
379     * its {@link #iterator}.  Each matching element is removed using
380     * {@link Iterator#remove()}.  If the collection's iterator does not
381     * support removal then an {@code UnsupportedOperationException} will be
382     * thrown on the first matching element.
383     *
384     * @param filter a predicate which returns {@code true} for elements to be
385     *        removed
386     * @return {@code true} if any elements were removed
387     * @throws NullPointerException if the specified filter is null
388     * @throws UnsupportedOperationException if elements cannot be removed
389     *         from this collection.  Implementations may throw this exception if a
390     *         matching element cannot be removed or if, in general, removal is not
391     *         supported.
392     * @since 1.8
393     */
394    default boolean removeIf(Predicate<? super E> filter) {
395        Objects.requireNonNull(filter);
396        boolean removed = false;
397        final Iterator<E> each = iterator();
398        while (each.hasNext()) {
399            if (filter.test(each.next())) {
400                each.remove();
401                removed = true;
402            }
403        }
404        return removed;
405    }
406
407    /**
408     * Retains only the elements in this collection that are contained in the
409     * specified collection (optional operation).  In other words, removes from
410     * this collection all of its elements that are not contained in the
411     * specified collection.
412     *
413     * @param c collection containing elements to be retained in this collection
414     * @return <tt>true</tt> if this collection changed as a result of the call
415     * @throws UnsupportedOperationException if the <tt>retainAll</tt> operation
416     *         is not supported by this collection
417     * @throws ClassCastException if the types of one or more elements
418     *         in this collection are incompatible with the specified
419     *         collection
420     *         (<a href="#optional-restrictions">optional</a>)
421     * @throws NullPointerException if this collection contains one or more
422     *         null elements and the specified collection does not permit null
423     *         elements
424     *         (<a href="#optional-restrictions">optional</a>),
425     *         or if the specified collection is null
426     * @see #remove(Object)
427     * @see #contains(Object)
428     */
429    boolean retainAll(Collection<?> c);
430
431    /**
432     * Removes all of the elements from this collection (optional operation).
433     * The collection will be empty after this method returns.
434     *
435     * @throws UnsupportedOperationException if the <tt>clear</tt> operation
436     *         is not supported by this collection
437     */
438    void clear();
439
440
441    // Comparison and hashing
442
443    /**
444     * Compares the specified object with this collection for equality. <p>
445     *
446     * While the <tt>Collection</tt> interface adds no stipulations to the
447     * general contract for the <tt>Object.equals</tt>, programmers who
448     * implement the <tt>Collection</tt> interface "directly" (in other words,
449     * create a class that is a <tt>Collection</tt> but is not a <tt>Set</tt>
450     * or a <tt>List</tt>) must exercise care if they choose to override the
451     * <tt>Object.equals</tt>.  It is not necessary to do so, and the simplest
452     * course of action is to rely on <tt>Object</tt>'s implementation, but
453     * the implementor may wish to implement a "value comparison" in place of
454     * the default "reference comparison."  (The <tt>List</tt> and
455     * <tt>Set</tt> interfaces mandate such value comparisons.)<p>
456     *
457     * The general contract for the <tt>Object.equals</tt> method states that
458     * equals must be symmetric (in other words, <tt>a.equals(b)</tt> if and
459     * only if <tt>b.equals(a)</tt>).  The contracts for <tt>List.equals</tt>
460     * and <tt>Set.equals</tt> state that lists are only equal to other lists,
461     * and sets to other sets.  Thus, a custom <tt>equals</tt> method for a
462     * collection class that implements neither the <tt>List</tt> nor
463     * <tt>Set</tt> interface must return <tt>false</tt> when this collection
464     * is compared to any list or set.  (By the same logic, it is not possible
465     * to write a class that correctly implements both the <tt>Set</tt> and
466     * <tt>List</tt> interfaces.)
467     *
468     * @param o object to be compared for equality with this collection
469     * @return <tt>true</tt> if the specified object is equal to this
470     * collection
471     *
472     * @see Object#equals(Object)
473     * @see Set#equals(Object)
474     * @see List#equals(Object)
475     */
476    boolean equals(Object o);
477
478    /**
479     * Returns the hash code value for this collection.  While the
480     * <tt>Collection</tt> interface adds no stipulations to the general
481     * contract for the <tt>Object.hashCode</tt> method, programmers should
482     * take note that any class that overrides the <tt>Object.equals</tt>
483     * method must also override the <tt>Object.hashCode</tt> method in order
484     * to satisfy the general contract for the <tt>Object.hashCode</tt> method.
485     * In particular, <tt>c1.equals(c2)</tt> implies that
486     * <tt>c1.hashCode()==c2.hashCode()</tt>.
487     *
488     * @return the hash code value for this collection
489     *
490     * @see Object#hashCode()
491     * @see Object#equals(Object)
492     */
493    int hashCode();
494
495    // TODO: Restore links to #stream and #parallelStream.
496    /**
497     * Creates a {@link Spliterator} over the elements in this collection.
498     *
499     * Implementations should document characteristic values reported by the
500     * spliterator.  Such characteristic values are not required to be reported
501     * if the spliterator reports {@link Spliterator#SIZED} and this collection
502     * contains no elements.
503     *
504     * <p>The default implementation should be overridden by subclasses that
505     * can return a more efficient spliterator.  In order to
506     * preserve expected laziness behavior for the {@code stream} and
507     * {@code parallelStream()}} methods, spliterators should either have the
508     * characteristic of {@code IMMUTABLE} or {@code CONCURRENT}, or be
509     * <em><a href="Spliterator.html#binding">late-binding</a></em>.
510     * If none of these is practical, the overriding class should describe the
511     * spliterator's documented policy of binding and structural interference,
512     * and should override the {@code stream} and {@code parallelStream}
513     * methods to create streams using a {@code Supplier} of the spliterator,
514     * as in:
515     * <pre>{@code
516     *     Stream<E> s = StreamSupport.stream(() -> spliterator(), spliteratorCharacteristics)
517     * }</pre>
518     * <p>These requirements ensure that streams produced by the
519     * {@code stream} and {@code parallelStream} methods will reflect the
520     * contents of the collection as of initiation of the terminal stream
521     * operation.
522     *
523     * @implSpec
524     * The default implementation creates a
525     * <em><a href="Spliterator.html#binding">late-binding</a></em> spliterator
526     * from the collections's {@code Iterator}.  The spliterator inherits the
527     * <em>fail-fast</em> properties of the collection's iterator.
528     * <p>
529     * The created {@code Spliterator} reports {@link Spliterator#SIZED}.
530     *
531     * @implNote
532     * The created {@code Spliterator} additionally reports
533     * {@link Spliterator#SUBSIZED}.
534     *
535     * <p>If a spliterator covers no elements then the reporting of additional
536     * characteristic values, beyond that of {@code SIZED} and {@code SUBSIZED},
537     * does not aid clients to control, specialize or simplify computation.
538     * However, this does enable shared use of an immutable and empty
539     * spliterator instance (see {@link Spliterators#emptySpliterator()}) for
540     * empty collections, and enables clients to determine if such a spliterator
541     * covers no elements.
542     *
543     * @return a {@code Spliterator} over the elements in this collection
544     * @since 1.8
545     */
546    @Override
547    default Spliterator<E> spliterator() {
548        return Spliterators.spliterator(this, 0);
549    }
550}
551