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