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