Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/java.base/share/classes/java/util/Collection.java
41152 views
1
/*
2
* Copyright (c) 1997, 2018, 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
26
package java.util;
27
28
import java.util.function.IntFunction;
29
import java.util.function.Predicate;
30
import java.util.stream.Stream;
31
import java.util.stream.StreamSupport;
32
33
/**
34
* The root interface in the <i>collection hierarchy</i>. A collection
35
* represents a group of objects, known as its <i>elements</i>. Some
36
* collections allow duplicate elements and others do not. Some are ordered
37
* and others unordered. The JDK does not provide any <i>direct</i>
38
* implementations of this interface: it provides implementations of more
39
* specific subinterfaces like {@code Set} and {@code List}. This interface
40
* is typically used to pass collections around and manipulate them where
41
* maximum generality is desired.
42
*
43
* <p><i>Bags</i> or <i>multisets</i> (unordered collections that may contain
44
* duplicate elements) should implement this interface directly.
45
*
46
* <p>All general-purpose {@code Collection} implementation classes (which
47
* typically implement {@code Collection} indirectly through one of its
48
* subinterfaces) should provide two "standard" constructors: a void (no
49
* arguments) constructor, which creates an empty collection, and a
50
* constructor with a single argument of type {@code Collection}, which
51
* creates a new collection with the same elements as its argument. In
52
* effect, the latter constructor allows the user to copy any collection,
53
* producing an equivalent collection of the desired implementation type.
54
* There is no way to enforce this convention (as interfaces cannot contain
55
* constructors) but all of the general-purpose {@code Collection}
56
* implementations in the Java platform libraries comply.
57
*
58
* <p>Certain methods are specified to be
59
* <i>optional</i>. If a collection implementation doesn't implement a
60
* particular operation, it should define the corresponding method to throw
61
* {@code UnsupportedOperationException}. Such methods are marked "optional
62
* operation" in method specifications of the collections interfaces.
63
*
64
* <p><a id="optional-restrictions"></a>Some collection implementations
65
* have restrictions on the elements that they may contain.
66
* For example, some implementations prohibit null elements,
67
* and some have restrictions on the types of their elements. Attempting to
68
* add an ineligible element throws an unchecked exception, typically
69
* {@code NullPointerException} or {@code ClassCastException}. Attempting
70
* to query the presence of an ineligible element may throw an exception,
71
* or it may simply return false; some implementations will exhibit the former
72
* behavior and some will exhibit the latter. More generally, attempting an
73
* operation on an ineligible element whose completion would not result in
74
* the insertion of an ineligible element into the collection may throw an
75
* exception or it may succeed, at the option of the implementation.
76
* Such exceptions are marked as "optional" in the specification for this
77
* interface.
78
*
79
* <p>It is up to each collection to determine its own synchronization
80
* policy. In the absence of a stronger guarantee by the
81
* implementation, undefined behavior may result from the invocation
82
* of any method on a collection that is being mutated by another
83
* thread; this includes direct invocations, passing the collection to
84
* a method that might perform invocations, and using an existing
85
* iterator to examine the collection.
86
*
87
* <p>Many methods in Collections Framework interfaces are defined in
88
* terms of the {@link Object#equals(Object) equals} method. For example,
89
* the specification for the {@link #contains(Object) contains(Object o)}
90
* method says: "returns {@code true} if and only if this collection
91
* contains at least one element {@code e} such that
92
* {@code (o==null ? e==null : o.equals(e))}." This specification should
93
* <i>not</i> be construed to imply that invoking {@code Collection.contains}
94
* with a non-null argument {@code o} will cause {@code o.equals(e)} to be
95
* invoked for any element {@code e}. Implementations are free to implement
96
* optimizations whereby the {@code equals} invocation is avoided, for
97
* example, by first comparing the hash codes of the two elements. (The
98
* {@link Object#hashCode()} specification guarantees that two objects with
99
* unequal hash codes cannot be equal.) More generally, implementations of
100
* the various Collections Framework interfaces are free to take advantage of
101
* the specified behavior of underlying {@link Object} methods wherever the
102
* implementor deems it appropriate.
103
*
104
* <p>Some collection operations which perform recursive traversal of the
105
* collection may fail with an exception for self-referential instances where
106
* the collection directly or indirectly contains itself. This includes the
107
* {@code clone()}, {@code equals()}, {@code hashCode()} and {@code toString()}
108
* methods. Implementations may optionally handle the self-referential scenario,
109
* however most current implementations do not do so.
110
*
111
* <h2><a id="view">View Collections</a></h2>
112
*
113
* <p>Most collections manage storage for elements they contain. By contrast, <i>view
114
* collections</i> themselves do not store elements, but instead they rely on a
115
* backing collection to store the actual elements. Operations that are not handled
116
* by the view collection itself are delegated to the backing collection. Examples of
117
* view collections include the wrapper collections returned by methods such as
118
* {@link Collections#checkedCollection Collections.checkedCollection},
119
* {@link Collections#synchronizedCollection Collections.synchronizedCollection}, and
120
* {@link Collections#unmodifiableCollection Collections.unmodifiableCollection}.
121
* Other examples of view collections include collections that provide a
122
* different representation of the same elements, for example, as
123
* provided by {@link List#subList List.subList},
124
* {@link NavigableSet#subSet NavigableSet.subSet}, or
125
* {@link Map#entrySet Map.entrySet}.
126
* Any changes made to the backing collection are visible in the view collection.
127
* Correspondingly, any changes made to the view collection &mdash; if changes
128
* are permitted &mdash; are written through to the backing collection.
129
* Although they technically aren't collections, instances of
130
* {@link Iterator} and {@link ListIterator} can also allow modifications
131
* to be written through to the backing collection, and in some cases,
132
* modifications to the backing collection will be visible to the Iterator
133
* during iteration.
134
*
135
* <h2><a id="unmodifiable">Unmodifiable Collections</a></h2>
136
*
137
* <p>Certain methods of this interface are considered "destructive" and are called
138
* "mutator" methods in that they modify the group of objects contained within
139
* the collection on which they operate. They can be specified to throw
140
* {@code UnsupportedOperationException} if this collection implementation
141
* does not support the operation. Such methods should (but are not required
142
* to) throw an {@code UnsupportedOperationException} if the invocation would
143
* have no effect on the collection. For example, consider a collection that
144
* does not support the {@link #add add} operation. What will happen if the
145
* {@link #addAll addAll} method is invoked on this collection, with an empty
146
* collection as the argument? The addition of zero elements has no effect,
147
* so it is permissible for this collection simply to do nothing and not to throw
148
* an exception. However, it is recommended that such cases throw an exception
149
* unconditionally, as throwing only in certain cases can lead to
150
* programming errors.
151
*
152
* <p>An <i>unmodifiable collection</i> is a collection, all of whose
153
* mutator methods (as defined above) are specified to throw
154
* {@code UnsupportedOperationException}. Such a collection thus cannot be
155
* modified by calling any methods on it. For a collection to be properly
156
* unmodifiable, any view collections derived from it must also be unmodifiable.
157
* For example, if a List is unmodifiable, the List returned by
158
* {@link List#subList List.subList} is also unmodifiable.
159
*
160
* <p>An unmodifiable collection is not necessarily immutable. If the
161
* contained elements are mutable, the entire collection is clearly
162
* mutable, even though it might be unmodifiable. For example, consider
163
* two unmodifiable lists containing mutable elements. The result of calling
164
* {@code list1.equals(list2)} might differ from one call to the next if
165
* the elements had been mutated, even though both lists are unmodifiable.
166
* However, if an unmodifiable collection contains all immutable elements,
167
* it can be considered effectively immutable.
168
*
169
* <h2><a id="unmodview">Unmodifiable View Collections</a></h2>
170
*
171
* <p>An <i>unmodifiable view collection</i> is a collection that is unmodifiable
172
* and that is also a view onto a backing collection. Its mutator methods throw
173
* {@code UnsupportedOperationException}, as described above, while
174
* reading and querying methods are delegated to the backing collection.
175
* The effect is to provide read-only access to the backing collection.
176
* This is useful for a component to provide users with read access to
177
* an internal collection, while preventing them from modifying such
178
* collections unexpectedly. Examples of unmodifiable view collections
179
* are those returned by the
180
* {@link Collections#unmodifiableCollection Collections.unmodifiableCollection},
181
* {@link Collections#unmodifiableList Collections.unmodifiableList}, and
182
* related methods.
183
*
184
* <p>Note that changes to the backing collection might still be possible,
185
* and if they occur, they are visible through the unmodifiable view. Thus,
186
* an unmodifiable view collection is not necessarily immutable. However,
187
* if the backing collection of an unmodifiable view is effectively immutable,
188
* or if the only reference to the backing collection is through an
189
* unmodifiable view, the view can be considered effectively immutable.
190
*
191
* <h2><a id="serializable">Serializability of Collections</a></h2>
192
*
193
* <p>Serializability of collections is optional. As such, none of the collections
194
* interfaces are declared to implement the {@link java.io.Serializable} interface.
195
* However, serializability is regarded as being generally useful, so most collection
196
* implementations are serializable.
197
*
198
* <p>The collection implementations that are public classes (such as {@code ArrayList}
199
* or {@code HashMap}) are declared to implement the {@code Serializable} interface if they
200
* are in fact serializable. Some collections implementations are not public classes,
201
* such as the <a href="#unmodifiable">unmodifiable collections.</a> In such cases, the
202
* serializability of such collections is described in the specification of the method
203
* that creates them, or in some other suitable place. In cases where the serializability
204
* of a collection is not specified, there is no guarantee about the serializability of such
205
* collections. In particular, many <a href="#view">view collections</a> are not serializable.
206
*
207
* <p>A collection implementation that implements the {@code Serializable} interface cannot
208
* be guaranteed to be serializable. The reason is that in general, collections
209
* contain elements of other types, and it is not possible to determine statically
210
* whether instances of some element type are actually serializable. For example, consider
211
* a serializable {@code Collection<E>}, where {@code E} does not implement the
212
* {@code Serializable} interface. The collection may be serializable, if it contains only
213
* elements of some serializable subtype of {@code E}, or if it is empty. Collections are
214
* thus said to be <i>conditionally serializable,</i> as the serializability of the collection
215
* as a whole depends on whether the collection itself is serializable and on whether all
216
* contained elements are also serializable.
217
*
218
* <p>An additional case occurs with instances of {@link SortedSet} and {@link SortedMap}.
219
* These collections can be created with a {@link Comparator} that imposes an ordering on
220
* the set elements or map keys. Such a collection is serializable only if the provided
221
* {@code Comparator} is also serializable.
222
*
223
* <p>This interface is a member of the
224
* <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
225
* Java Collections Framework</a>.
226
*
227
* @implSpec
228
* The default method implementations (inherited or otherwise) do not apply any
229
* synchronization protocol. If a {@code Collection} implementation has a
230
* specific synchronization protocol, then it must override default
231
* implementations to apply that protocol.
232
*
233
* @param <E> the type of elements in this collection
234
*
235
* @author Josh Bloch
236
* @author Neal Gafter
237
* @see Set
238
* @see List
239
* @see Map
240
* @see SortedSet
241
* @see SortedMap
242
* @see HashSet
243
* @see TreeSet
244
* @see ArrayList
245
* @see LinkedList
246
* @see Vector
247
* @see Collections
248
* @see Arrays
249
* @see AbstractCollection
250
* @since 1.2
251
*/
252
253
public interface Collection<E> extends Iterable<E> {
254
// Query Operations
255
256
/**
257
* Returns the number of elements in this collection. If this collection
258
* contains more than {@code Integer.MAX_VALUE} elements, returns
259
* {@code Integer.MAX_VALUE}.
260
*
261
* @return the number of elements in this collection
262
*/
263
int size();
264
265
/**
266
* Returns {@code true} if this collection contains no elements.
267
*
268
* @return {@code true} if this collection contains no elements
269
*/
270
boolean isEmpty();
271
272
/**
273
* Returns {@code true} if this collection contains the specified element.
274
* More formally, returns {@code true} if and only if this collection
275
* contains at least one element {@code e} such that
276
* {@code Objects.equals(o, e)}.
277
*
278
* @param o element whose presence in this collection is to be tested
279
* @return {@code true} if this collection contains the specified
280
* element
281
* @throws ClassCastException if the type of the specified element
282
* is incompatible with this collection
283
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
284
* @throws NullPointerException if the specified element is null and this
285
* collection does not permit null elements
286
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
287
*/
288
boolean contains(Object o);
289
290
/**
291
* Returns an iterator over the elements in this collection. There are no
292
* guarantees concerning the order in which the elements are returned
293
* (unless this collection is an instance of some class that provides a
294
* guarantee).
295
*
296
* @return an {@code Iterator} over the elements in this collection
297
*/
298
Iterator<E> iterator();
299
300
/**
301
* Returns an array containing all of the elements in this collection.
302
* If this collection makes any guarantees as to what order its elements
303
* are returned by its iterator, this method must return the elements in
304
* the same order. The returned array's {@linkplain Class#getComponentType
305
* runtime component type} is {@code Object}.
306
*
307
* <p>The returned array will be "safe" in that no references to it are
308
* maintained by this collection. (In other words, this method must
309
* allocate a new array even if this collection is backed by an array).
310
* The caller is thus free to modify the returned array.
311
*
312
* @apiNote
313
* This method acts as a bridge between array-based and collection-based APIs.
314
* It returns an array whose runtime type is {@code Object[]}.
315
* Use {@link #toArray(Object[]) toArray(T[])} to reuse an existing
316
* array, or use {@link #toArray(IntFunction)} to control the runtime type
317
* of the array.
318
*
319
* @return an array, whose {@linkplain Class#getComponentType runtime component
320
* type} is {@code Object}, containing all of the elements in this collection
321
*/
322
Object[] toArray();
323
324
/**
325
* Returns an array containing all of the elements in this collection;
326
* the runtime type of the returned array is that of the specified array.
327
* If the collection fits in the specified array, it is returned therein.
328
* Otherwise, a new array is allocated with the runtime type of the
329
* specified array and the size of this collection.
330
*
331
* <p>If this collection fits in the specified array with room to spare
332
* (i.e., the array has more elements than this collection), the element
333
* in the array immediately following the end of the collection is set to
334
* {@code null}. (This is useful in determining the length of this
335
* collection <i>only</i> if the caller knows that this collection does
336
* not contain any {@code null} elements.)
337
*
338
* <p>If this collection makes any guarantees as to what order its elements
339
* are returned by its iterator, this method must return the elements in
340
* the same order.
341
*
342
* @apiNote
343
* This method acts as a bridge between array-based and collection-based APIs.
344
* It allows an existing array to be reused under certain circumstances.
345
* Use {@link #toArray()} to create an array whose runtime type is {@code Object[]},
346
* or use {@link #toArray(IntFunction)} to control the runtime type of
347
* the array.
348
*
349
* <p>Suppose {@code x} is a collection known to contain only strings.
350
* The following code can be used to dump the collection into a previously
351
* allocated {@code String} array:
352
*
353
* <pre>
354
* String[] y = new String[SIZE];
355
* ...
356
* y = x.toArray(y);</pre>
357
*
358
* <p>The return value is reassigned to the variable {@code y}, because a
359
* new array will be allocated and returned if the collection {@code x} has
360
* too many elements to fit into the existing array {@code y}.
361
*
362
* <p>Note that {@code toArray(new Object[0])} is identical in function to
363
* {@code toArray()}.
364
*
365
* @param <T> the component type of the array to contain the collection
366
* @param a the array into which the elements of this collection are to be
367
* stored, if it is big enough; otherwise, a new array of the same
368
* runtime type is allocated for this purpose.
369
* @return an array containing all of the elements in this collection
370
* @throws ArrayStoreException if the runtime type of any element in this
371
* collection is not assignable to the {@linkplain Class#getComponentType
372
* runtime component type} of the specified array
373
* @throws NullPointerException if the specified array is null
374
*/
375
<T> T[] toArray(T[] a);
376
377
/**
378
* Returns an array containing all of the elements in this collection,
379
* using the provided {@code generator} function to allocate the returned array.
380
*
381
* <p>If this collection makes any guarantees as to what order its elements
382
* are returned by its iterator, this method must return the elements in
383
* the same order.
384
*
385
* @apiNote
386
* This method acts as a bridge between array-based and collection-based APIs.
387
* It allows creation of an array of a particular runtime type. Use
388
* {@link #toArray()} to create an array whose runtime type is {@code Object[]},
389
* or use {@link #toArray(Object[]) toArray(T[])} to reuse an existing array.
390
*
391
* <p>Suppose {@code x} is a collection known to contain only strings.
392
* The following code can be used to dump the collection into a newly
393
* allocated array of {@code String}:
394
*
395
* <pre>
396
* String[] y = x.toArray(String[]::new);</pre>
397
*
398
* @implSpec
399
* The default implementation calls the generator function with zero
400
* and then passes the resulting array to {@link #toArray(Object[]) toArray(T[])}.
401
*
402
* @param <T> the component type of the array to contain the collection
403
* @param generator a function which produces a new array of the desired
404
* type and the provided length
405
* @return an array containing all of the elements in this collection
406
* @throws ArrayStoreException if the runtime type of any element in this
407
* collection is not assignable to the {@linkplain Class#getComponentType
408
* runtime component type} of the generated array
409
* @throws NullPointerException if the generator function is null
410
* @since 11
411
*/
412
default <T> T[] toArray(IntFunction<T[]> generator) {
413
return toArray(generator.apply(0));
414
}
415
416
// Modification Operations
417
418
/**
419
* Ensures that this collection contains the specified element (optional
420
* operation). Returns {@code true} if this collection changed as a
421
* result of the call. (Returns {@code false} if this collection does
422
* not permit duplicates and already contains the specified element.)<p>
423
*
424
* Collections that support this operation may place limitations on what
425
* elements may be added to this collection. In particular, some
426
* collections will refuse to add {@code null} elements, and others will
427
* impose restrictions on the type of elements that may be added.
428
* Collection classes should clearly specify in their documentation any
429
* restrictions on what elements may be added.<p>
430
*
431
* If a collection refuses to add a particular element for any reason
432
* other than that it already contains the element, it <i>must</i> throw
433
* an exception (rather than returning {@code false}). This preserves
434
* the invariant that a collection always contains the specified element
435
* after this call returns.
436
*
437
* @param e element whose presence in this collection is to be ensured
438
* @return {@code true} if this collection changed as a result of the
439
* call
440
* @throws UnsupportedOperationException if the {@code add} operation
441
* is not supported by this collection
442
* @throws ClassCastException if the class of the specified element
443
* prevents it from being added to this collection
444
* @throws NullPointerException if the specified element is null and this
445
* collection does not permit null elements
446
* @throws IllegalArgumentException if some property of the element
447
* prevents it from being added to this collection
448
* @throws IllegalStateException if the element cannot be added at this
449
* time due to insertion restrictions
450
*/
451
boolean add(E e);
452
453
/**
454
* Removes a single instance of the specified element from this
455
* collection, if it is present (optional operation). More formally,
456
* removes an element {@code e} such that
457
* {@code Objects.equals(o, e)}, if
458
* this collection contains one or more such elements. Returns
459
* {@code true} if this collection contained the specified element (or
460
* equivalently, if this collection changed as a result of the call).
461
*
462
* @param o element to be removed from this collection, if present
463
* @return {@code true} if an element was removed as a result of this call
464
* @throws ClassCastException if the type of the specified element
465
* is incompatible with this collection
466
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
467
* @throws NullPointerException if the specified element is null and this
468
* collection does not permit null elements
469
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
470
* @throws UnsupportedOperationException if the {@code remove} operation
471
* is not supported by this collection
472
*/
473
boolean remove(Object o);
474
475
476
// Bulk Operations
477
478
/**
479
* Returns {@code true} if this collection contains all of the elements
480
* in the specified collection.
481
*
482
* @param c collection to be checked for containment in this collection
483
* @return {@code true} if this collection contains all of the elements
484
* in the specified collection
485
* @throws ClassCastException if the types of one or more elements
486
* in the specified collection are incompatible with this
487
* collection
488
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
489
* @throws NullPointerException if the specified collection contains one
490
* or more null elements and this collection does not permit null
491
* elements
492
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>),
493
* or if the specified collection is null.
494
* @see #contains(Object)
495
*/
496
boolean containsAll(Collection<?> c);
497
498
/**
499
* Adds all of the elements in the specified collection to this collection
500
* (optional operation). The behavior of this operation is undefined if
501
* the specified collection is modified while the operation is in progress.
502
* (This implies that the behavior of this call is undefined if the
503
* specified collection is this collection, and this collection is
504
* nonempty.)
505
*
506
* @param c collection containing elements to be added to this collection
507
* @return {@code true} if this collection changed as a result of the call
508
* @throws UnsupportedOperationException if the {@code addAll} operation
509
* is not supported by this collection
510
* @throws ClassCastException if the class of an element of the specified
511
* collection prevents it from being added to this collection
512
* @throws NullPointerException if the specified collection contains a
513
* null element and this collection does not permit null elements,
514
* or if the specified collection is null
515
* @throws IllegalArgumentException if some property of an element of the
516
* specified collection prevents it from being added to this
517
* collection
518
* @throws IllegalStateException if not all the elements can be added at
519
* this time due to insertion restrictions
520
* @see #add(Object)
521
*/
522
boolean addAll(Collection<? extends E> c);
523
524
/**
525
* Removes all of this collection's elements that are also contained in the
526
* specified collection (optional operation). After this call returns,
527
* this collection will contain no elements in common with the specified
528
* collection.
529
*
530
* @param c collection containing elements to be removed from this collection
531
* @return {@code true} if this collection changed as a result of the
532
* call
533
* @throws UnsupportedOperationException if the {@code removeAll} method
534
* is not supported by this collection
535
* @throws ClassCastException if the types of one or more elements
536
* in this collection are incompatible with the specified
537
* collection
538
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
539
* @throws NullPointerException if this collection contains one or more
540
* null elements and the specified collection does not support
541
* null elements
542
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>),
543
* or if the specified collection is null
544
* @see #remove(Object)
545
* @see #contains(Object)
546
*/
547
boolean removeAll(Collection<?> c);
548
549
/**
550
* Removes all of the elements of this collection that satisfy the given
551
* predicate. Errors or runtime exceptions thrown during iteration or by
552
* the predicate are relayed to the caller.
553
*
554
* @implSpec
555
* The default implementation traverses all elements of the collection using
556
* its {@link #iterator}. Each matching element is removed using
557
* {@link Iterator#remove()}. If the collection's iterator does not
558
* support removal then an {@code UnsupportedOperationException} will be
559
* thrown on the first matching element.
560
*
561
* @param filter a predicate which returns {@code true} for elements to be
562
* removed
563
* @return {@code true} if any elements were removed
564
* @throws NullPointerException if the specified filter is null
565
* @throws UnsupportedOperationException if elements cannot be removed
566
* from this collection. Implementations may throw this exception if a
567
* matching element cannot be removed or if, in general, removal is not
568
* supported.
569
* @since 1.8
570
*/
571
default boolean removeIf(Predicate<? super E> filter) {
572
Objects.requireNonNull(filter);
573
boolean removed = false;
574
final Iterator<E> each = iterator();
575
while (each.hasNext()) {
576
if (filter.test(each.next())) {
577
each.remove();
578
removed = true;
579
}
580
}
581
return removed;
582
}
583
584
/**
585
* Retains only the elements in this collection that are contained in the
586
* specified collection (optional operation). In other words, removes from
587
* this collection all of its elements that are not contained in the
588
* specified collection.
589
*
590
* @param c collection containing elements to be retained in this collection
591
* @return {@code true} if this collection changed as a result of the call
592
* @throws UnsupportedOperationException if the {@code retainAll} operation
593
* is not supported by this collection
594
* @throws ClassCastException if the types of one or more elements
595
* in this collection are incompatible with the specified
596
* collection
597
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
598
* @throws NullPointerException if this collection contains one or more
599
* null elements and the specified collection does not permit null
600
* elements
601
* (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>),
602
* or if the specified collection is null
603
* @see #remove(Object)
604
* @see #contains(Object)
605
*/
606
boolean retainAll(Collection<?> c);
607
608
/**
609
* Removes all of the elements from this collection (optional operation).
610
* The collection will be empty after this method returns.
611
*
612
* @throws UnsupportedOperationException if the {@code clear} operation
613
* is not supported by this collection
614
*/
615
void clear();
616
617
618
// Comparison and hashing
619
620
/**
621
* Compares the specified object with this collection for equality. <p>
622
*
623
* While the {@code Collection} interface adds no stipulations to the
624
* general contract for the {@code Object.equals}, programmers who
625
* implement the {@code Collection} interface "directly" (in other words,
626
* create a class that is a {@code Collection} but is not a {@code Set}
627
* or a {@code List}) must exercise care if they choose to override the
628
* {@code Object.equals}. It is not necessary to do so, and the simplest
629
* course of action is to rely on {@code Object}'s implementation, but
630
* the implementor may wish to implement a "value comparison" in place of
631
* the default "reference comparison." (The {@code List} and
632
* {@code Set} interfaces mandate such value comparisons.)<p>
633
*
634
* The general contract for the {@code Object.equals} method states that
635
* equals must be symmetric (in other words, {@code a.equals(b)} if and
636
* only if {@code b.equals(a)}). The contracts for {@code List.equals}
637
* and {@code Set.equals} state that lists are only equal to other lists,
638
* and sets to other sets. Thus, a custom {@code equals} method for a
639
* collection class that implements neither the {@code List} nor
640
* {@code Set} interface must return {@code false} when this collection
641
* is compared to any list or set. (By the same logic, it is not possible
642
* to write a class that correctly implements both the {@code Set} and
643
* {@code List} interfaces.)
644
*
645
* @param o object to be compared for equality with this collection
646
* @return {@code true} if the specified object is equal to this
647
* collection
648
*
649
* @see Object#equals(Object)
650
* @see Set#equals(Object)
651
* @see List#equals(Object)
652
*/
653
boolean equals(Object o);
654
655
/**
656
* Returns the hash code value for this collection. While the
657
* {@code Collection} interface adds no stipulations to the general
658
* contract for the {@code Object.hashCode} method, programmers should
659
* take note that any class that overrides the {@code Object.equals}
660
* method must also override the {@code Object.hashCode} method in order
661
* to satisfy the general contract for the {@code Object.hashCode} method.
662
* In particular, {@code c1.equals(c2)} implies that
663
* {@code c1.hashCode()==c2.hashCode()}.
664
*
665
* @return the hash code value for this collection
666
*
667
* @see Object#hashCode()
668
* @see Object#equals(Object)
669
*/
670
int hashCode();
671
672
/**
673
* Creates a {@link Spliterator} over the elements in this collection.
674
*
675
* Implementations should document characteristic values reported by the
676
* spliterator. Such characteristic values are not required to be reported
677
* if the spliterator reports {@link Spliterator#SIZED} and this collection
678
* contains no elements.
679
*
680
* <p>The default implementation should be overridden by subclasses that
681
* can return a more efficient spliterator. In order to
682
* preserve expected laziness behavior for the {@link #stream()} and
683
* {@link #parallelStream()} methods, spliterators should either have the
684
* characteristic of {@code IMMUTABLE} or {@code CONCURRENT}, or be
685
* <em><a href="Spliterator.html#binding">late-binding</a></em>.
686
* If none of these is practical, the overriding class should describe the
687
* spliterator's documented policy of binding and structural interference,
688
* and should override the {@link #stream()} and {@link #parallelStream()}
689
* methods to create streams using a {@code Supplier} of the spliterator,
690
* as in:
691
* <pre>{@code
692
* Stream<E> s = StreamSupport.stream(() -> spliterator(), spliteratorCharacteristics)
693
* }</pre>
694
* <p>These requirements ensure that streams produced by the
695
* {@link #stream()} and {@link #parallelStream()} methods will reflect the
696
* contents of the collection as of initiation of the terminal stream
697
* operation.
698
*
699
* @implSpec
700
* The default implementation creates a
701
* <em><a href="Spliterator.html#binding">late-binding</a></em> spliterator
702
* from the collection's {@code Iterator}. The spliterator inherits the
703
* <em>fail-fast</em> properties of the collection's iterator.
704
* <p>
705
* The created {@code Spliterator} reports {@link Spliterator#SIZED}.
706
*
707
* @implNote
708
* The created {@code Spliterator} additionally reports
709
* {@link Spliterator#SUBSIZED}.
710
*
711
* <p>If a spliterator covers no elements then the reporting of additional
712
* characteristic values, beyond that of {@code SIZED} and {@code SUBSIZED},
713
* does not aid clients to control, specialize or simplify computation.
714
* However, this does enable shared use of an immutable and empty
715
* spliterator instance (see {@link Spliterators#emptySpliterator()}) for
716
* empty collections, and enables clients to determine if such a spliterator
717
* covers no elements.
718
*
719
* @return a {@code Spliterator} over the elements in this collection
720
* @since 1.8
721
*/
722
@Override
723
default Spliterator<E> spliterator() {
724
return Spliterators.spliterator(this, 0);
725
}
726
727
/**
728
* Returns a sequential {@code Stream} with this collection as its source.
729
*
730
* <p>This method should be overridden when the {@link #spliterator()}
731
* method cannot return a spliterator that is {@code IMMUTABLE},
732
* {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
733
* for details.)
734
*
735
* @implSpec
736
* The default implementation creates a sequential {@code Stream} from the
737
* collection's {@code Spliterator}.
738
*
739
* @return a sequential {@code Stream} over the elements in this collection
740
* @since 1.8
741
*/
742
default Stream<E> stream() {
743
return StreamSupport.stream(spliterator(), false);
744
}
745
746
/**
747
* Returns a possibly parallel {@code Stream} with this collection as its
748
* source. It is allowable for this method to return a sequential stream.
749
*
750
* <p>This method should be overridden when the {@link #spliterator()}
751
* method cannot return a spliterator that is {@code IMMUTABLE},
752
* {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
753
* for details.)
754
*
755
* @implSpec
756
* The default implementation creates a parallel {@code Stream} from the
757
* collection's {@code Spliterator}.
758
*
759
* @return a possibly parallel {@code Stream} over the elements in this
760
* collection
761
* @since 1.8
762
*/
763
default Stream<E> parallelStream() {
764
return StreamSupport.stream(spliterator(), true);
765
}
766
}
767
768