• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 1997, 2020, 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.UnaryOperator;
29 
30 // Android-removed: removed link to collections framework docs
31 /**
32  * An ordered collection (also known as a <i>sequence</i>).  The user of this
33  * interface has precise control over where in the list each element is
34  * inserted.  The user can access elements by their integer index (position in
35  * the list), and search for elements in the list.<p>
36  *
37  * Unlike sets, lists typically allow duplicate elements.  More formally,
38  * lists typically allow pairs of elements {@code e1} and {@code e2}
39  * such that {@code e1.equals(e2)}, and they typically allow multiple
40  * null elements if they allow null elements at all.  It is not inconceivable
41  * that someone might wish to implement a list that prohibits duplicates, by
42  * throwing runtime exceptions when the user attempts to insert them, but we
43  * expect this usage to be rare.<p>
44  *
45  * The {@code List} interface places additional stipulations, beyond those
46  * specified in the {@code Collection} interface, on the contracts of the
47  * {@code iterator}, {@code add}, {@code remove}, {@code equals}, and
48  * {@code hashCode} methods.  Declarations for other inherited methods are
49  * also included here for convenience.<p>
50  *
51  * The {@code List} interface provides four methods for positional (indexed)
52  * access to list elements.  Lists (like Java arrays) are zero based.  Note
53  * that these operations may execute in time proportional to the index value
54  * for some implementations (the {@code LinkedList} class, for
55  * example). Thus, iterating over the elements in a list is typically
56  * preferable to indexing through it if the caller does not know the
57  * implementation.<p>
58  *
59  * The {@code List} interface provides a special iterator, called a
60  * {@code ListIterator}, that allows element insertion and replacement, and
61  * bidirectional access in addition to the normal operations that the
62  * {@code Iterator} interface provides.  A method is provided to obtain a
63  * list iterator that starts at a specified position in the list.<p>
64  *
65  * The {@code List} interface provides two methods to search for a specified
66  * object.  From a performance standpoint, these methods should be used with
67  * caution.  In many implementations they will perform costly linear
68  * searches.<p>
69  *
70  * The {@code List} interface provides two methods to efficiently insert and
71  * remove multiple elements at an arbitrary point in the list.<p>
72  *
73  * Note: While it is permissible for lists to contain themselves as elements,
74  * extreme caution is advised: the {@code equals} and {@code hashCode}
75  * methods are no longer well defined on such a list.
76  *
77  * <p>Some list implementations have restrictions on the elements that
78  * they may contain.  For example, some implementations prohibit null elements,
79  * and some have restrictions on the types of their elements.  Attempting to
80  * add an ineligible element throws an unchecked exception, typically
81  * {@code NullPointerException} or {@code ClassCastException}.  Attempting
82  * to query the presence of an ineligible element may throw an exception,
83  * or it may simply return false; some implementations will exhibit the former
84  * behavior and some will exhibit the latter.  More generally, attempting an
85  * operation on an ineligible element whose completion would not result in
86  * the insertion of an ineligible element into the list may throw an
87  * exception or it may succeed, at the option of the implementation.
88  * Such exceptions are marked as "optional" in the specification for this
89  * interface.
90  *
91  * <h2><a id="unmodifiable">Unmodifiable Lists</a></h2>
92  * <p>The {@link List#of(Object...) List.of} and
93  * {@link List#copyOf List.copyOf} static factory methods
94  * provide a convenient way to create unmodifiable lists. The {@code List}
95  * instances created by these methods have the following characteristics:
96  *
97  * <ul>
98  * <li>They are <a href="Collection.html#unmodifiable"><i>unmodifiable</i></a>. Elements cannot
99  * be added, removed, or replaced. Calling any mutator method on the List
100  * will always cause {@code UnsupportedOperationException} to be thrown.
101  * However, if the contained elements are themselves mutable,
102  * this may cause the List's contents to appear to change.
103  * <li>They disallow {@code null} elements. Attempts to create them with
104  * {@code null} elements result in {@code NullPointerException}.
105  * <li>They are serializable if all elements are serializable.
106  * <li>The order of elements in the list is the same as the order of the
107  * provided arguments, or of the elements in the provided array.
108  * <li>The lists and their {@link #subList(int, int) subList} views implement the
109  * {@link RandomAccess} interface.
110  * <li>They are <a href="../lang/doc-files/ValueBased.html">value-based</a>.
111  * Programmers should treat instances that are {@linkplain #equals(Object) equal}
112  * as interchangeable and should not use them for synchronization, or
113  * unpredictable behavior may occur. For example, in a future release,
114  * synchronization may fail. Callers should make no assumptions about the
115  * identity of the returned instances. Factories are free to
116  * create new instances or reuse existing ones.
117  * <li>They are serialized as specified on the
118  * <a href="{@docRoot}/serialized-form.html#java.util.CollSer">Serialized Form</a>
119  * page.
120  * </ul>
121  *
122  * @param <E> the type of elements in this list
123  *
124  * @author  Josh Bloch
125  * @author  Neal Gafter
126  * @see Collection
127  * @see Set
128  * @see ArrayList
129  * @see LinkedList
130  * @see Vector
131  * @see Arrays#asList(Object[])
132  * @see Collections#nCopies(int, Object)
133  * @see Collections#EMPTY_LIST
134  * @see AbstractList
135  * @see AbstractSequentialList
136  * @since 1.2
137  */
138 
139 public interface List<E> extends Collection<E> {
140     // Query Operations
141 
142     /**
143      * Returns the number of elements in this list.  If this list contains
144      * more than {@code Integer.MAX_VALUE} elements, returns
145      * {@code Integer.MAX_VALUE}.
146      *
147      * @return the number of elements in this list
148      */
size()149     int size();
150 
151     /**
152      * Returns {@code true} if this list contains no elements.
153      *
154      * @return {@code true} if this list contains no elements
155      */
isEmpty()156     boolean isEmpty();
157 
158     /**
159      * Returns {@code true} if this list contains the specified element.
160      * More formally, returns {@code true} if and only if this list contains
161      * at least one element {@code e} such that
162      * {@code Objects.equals(o, e)}.
163      *
164      * @param o element whose presence in this list is to be tested
165      * @return {@code true} if this list contains the specified element
166      * @throws ClassCastException if the type of the specified element
167      *         is incompatible with this list
168      * (<a href="Collection.html#optional-restrictions">optional</a>)
169      * @throws NullPointerException if the specified element is null and this
170      *         list does not permit null elements
171      * (<a href="Collection.html#optional-restrictions">optional</a>)
172      */
contains(Object o)173     boolean contains(Object o);
174 
175     /**
176      * Returns an iterator over the elements in this list in proper sequence.
177      *
178      * @return an iterator over the elements in this list in proper sequence
179      */
iterator()180     Iterator<E> iterator();
181 
182     /**
183      * Returns an array containing all of the elements in this list in proper
184      * sequence (from first to last element).
185      *
186      * <p>The returned array will be "safe" in that no references to it are
187      * maintained by this list.  (In other words, this method must
188      * allocate a new array even if this list is backed by an array).
189      * The caller is thus free to modify the returned array.
190      *
191      * <p>This method acts as bridge between array-based and collection-based
192      * APIs.
193      *
194      * @return an array containing all of the elements in this list in proper
195      *         sequence
196      * @see Arrays#asList(Object[])
197      */
toArray()198     Object[] toArray();
199 
200     /**
201      * Returns an array containing all of the elements in this list in
202      * proper sequence (from first to last element); the runtime type of
203      * the returned array is that of the specified array.  If the list fits
204      * in the specified array, it is returned therein.  Otherwise, a new
205      * array is allocated with the runtime type of the specified array and
206      * the size of this list.
207      *
208      * <p>If the list fits in the specified array with room to spare (i.e.,
209      * the array has more elements than the list), the element in the array
210      * immediately following the end of the list is set to {@code null}.
211      * (This is useful in determining the length of the list <i>only</i> if
212      * the caller knows that the list does not contain any null elements.)
213      *
214      * <p>Like the {@link #toArray()} method, this method acts as bridge between
215      * array-based and collection-based APIs.  Further, this method allows
216      * precise control over the runtime type of the output array, and may,
217      * under certain circumstances, be used to save allocation costs.
218      *
219      * <p>Suppose {@code x} is a list known to contain only strings.
220      * The following code can be used to dump the list into a newly
221      * allocated array of {@code String}:
222      *
223      * <pre>{@code
224      *     String[] y = x.toArray(new String[0]);
225      * }</pre>
226      *
227      * Note that {@code toArray(new Object[0])} is identical in function to
228      * {@code toArray()}.
229      *
230      * @param a the array into which the elements of this list are to
231      *          be stored, if it is big enough; otherwise, a new array of the
232      *          same runtime type is allocated for this purpose.
233      * @return an array containing the elements of this list
234      * @throws ArrayStoreException if the runtime type of the specified array
235      *         is not a supertype of the runtime type of every element in
236      *         this list
237      * @throws NullPointerException if the specified array is null
238      */
toArray(T[] a)239     <T> T[] toArray(T[] a);
240 
241 
242     // Modification Operations
243 
244     /**
245      * Appends the specified element to the end of this list (optional
246      * operation).
247      *
248      * <p>Lists that support this operation may place limitations on what
249      * elements may be added to this list.  In particular, some
250      * lists will refuse to add null elements, and others will impose
251      * restrictions on the type of elements that may be added.  List
252      * classes should clearly specify in their documentation any restrictions
253      * on what elements may be added.
254      *
255      * @param e element to be appended to this list
256      * @return {@code true} (as specified by {@link Collection#add})
257      * @throws UnsupportedOperationException if the {@code add} operation
258      *         is not supported by this list
259      * @throws ClassCastException if the class of the specified element
260      *         prevents it from being added to this list
261      * @throws NullPointerException if the specified element is null and this
262      *         list does not permit null elements
263      * @throws IllegalArgumentException if some property of this element
264      *         prevents it from being added to this list
265      */
add(E e)266     boolean add(E e);
267 
268     /**
269      * Removes the first occurrence of the specified element from this list,
270      * if it is present (optional operation).  If this list does not contain
271      * the element, it is unchanged.  More formally, removes the element with
272      * the lowest index {@code i} such that
273      * {@code Objects.equals(o, get(i))}
274      * (if such an element exists).  Returns {@code true} if this list
275      * contained the specified element (or equivalently, if this list changed
276      * as a result of the call).
277      *
278      * @param o element to be removed from this list, if present
279      * @return {@code true} if this list contained the specified element
280      * @throws ClassCastException if the type of the specified element
281      *         is incompatible with this list
282      * (<a href="Collection.html#optional-restrictions">optional</a>)
283      * @throws NullPointerException if the specified element is null and this
284      *         list does not permit null elements
285      * (<a href="Collection.html#optional-restrictions">optional</a>)
286      * @throws UnsupportedOperationException if the {@code remove} operation
287      *         is not supported by this list
288      */
remove(Object o)289     boolean remove(Object o);
290 
291 
292     // Bulk Modification Operations
293 
294     /**
295      * Returns {@code true} if this list contains all of the elements of the
296      * specified collection.
297      *
298      * @param  c collection to be checked for containment in this list
299      * @return {@code true} if this list contains all of the elements of the
300      *         specified collection
301      * @throws ClassCastException if the types of one or more elements
302      *         in the specified collection are incompatible with this
303      *         list
304      * (<a href="Collection.html#optional-restrictions">optional</a>)
305      * @throws NullPointerException if the specified collection contains one
306      *         or more null elements and this list does not permit null
307      *         elements
308      *         (<a href="Collection.html#optional-restrictions">optional</a>),
309      *         or if the specified collection is null
310      * @see #contains(Object)
311      */
containsAll(Collection<?> c)312     boolean containsAll(Collection<?> c);
313 
314     /**
315      * Appends all of the elements in the specified collection to the end of
316      * this list, in the order that they are returned by the specified
317      * collection's iterator (optional operation).  The behavior of this
318      * operation is undefined if the specified collection is modified while
319      * the operation is in progress.  (Note that this will occur if the
320      * specified collection is this list, and it's nonempty.)
321      *
322      * @param c collection containing elements to be added to this list
323      * @return {@code true} if this list changed as a result of the call
324      * @throws UnsupportedOperationException if the {@code addAll} operation
325      *         is not supported by this list
326      * @throws ClassCastException if the class of an element of the specified
327      *         collection prevents it from being added to this list
328      * @throws NullPointerException if the specified collection contains one
329      *         or more null elements and this list does not permit null
330      *         elements, or if the specified collection is null
331      * @throws IllegalArgumentException if some property of an element of the
332      *         specified collection prevents it from being added to this list
333      * @see #add(Object)
334      */
addAll(Collection<? extends E> c)335     boolean addAll(Collection<? extends E> c);
336 
337     /**
338      * Inserts all of the elements in the specified collection into this
339      * list at the specified position (optional operation).  Shifts the
340      * element currently at that position (if any) and any subsequent
341      * elements to the right (increases their indices).  The new elements
342      * will appear in this list in the order that they are returned by the
343      * specified collection's iterator.  The behavior of this operation is
344      * undefined if the specified collection is modified while the
345      * operation is in progress.  (Note that this will occur if the specified
346      * collection is this list, and it's nonempty.)
347      *
348      * @param index index at which to insert the first element from the
349      *              specified collection
350      * @param c collection containing elements to be added to this list
351      * @return {@code true} if this list changed as a result of the call
352      * @throws UnsupportedOperationException if the {@code addAll} operation
353      *         is not supported by this list
354      * @throws ClassCastException if the class of an element of the specified
355      *         collection prevents it from being added to this list
356      * @throws NullPointerException if the specified collection contains one
357      *         or more null elements and this list does not permit null
358      *         elements, or if the specified collection is null
359      * @throws IllegalArgumentException if some property of an element of the
360      *         specified collection prevents it from being added to this list
361      * @throws IndexOutOfBoundsException if the index is out of range
362      *         ({@code index < 0 || index > size()})
363      */
addAll(int index, Collection<? extends E> c)364     boolean addAll(int index, Collection<? extends E> c);
365 
366     /**
367      * Removes from this list all of its elements that are contained in the
368      * specified collection (optional operation).
369      *
370      * @param c collection containing elements to be removed from this list
371      * @return {@code true} if this list changed as a result of the call
372      * @throws UnsupportedOperationException if the {@code removeAll} operation
373      *         is not supported by this list
374      * @throws ClassCastException if the class of an element of this list
375      *         is incompatible with the specified collection
376      * (<a href="Collection.html#optional-restrictions">optional</a>)
377      * @throws NullPointerException if this list contains a null element and the
378      *         specified collection does not permit null elements
379      *         (<a href="Collection.html#optional-restrictions">optional</a>),
380      *         or if the specified collection is null
381      * @see #remove(Object)
382      * @see #contains(Object)
383      */
removeAll(Collection<?> c)384     boolean removeAll(Collection<?> c);
385 
386     /**
387      * Retains only the elements in this list that are contained in the
388      * specified collection (optional operation).  In other words, removes
389      * from this list all of its elements that are not contained in the
390      * specified collection.
391      *
392      * @param c collection containing elements to be retained in this list
393      * @return {@code true} if this list changed as a result of the call
394      * @throws UnsupportedOperationException if the {@code retainAll} operation
395      *         is not supported by this list
396      * @throws ClassCastException if the class of an element of this list
397      *         is incompatible with the specified collection
398      * (<a href="Collection.html#optional-restrictions">optional</a>)
399      * @throws NullPointerException if this list contains a null element and the
400      *         specified collection does not permit null elements
401      *         (<a href="Collection.html#optional-restrictions">optional</a>),
402      *         or if the specified collection is null
403      * @see #remove(Object)
404      * @see #contains(Object)
405      */
retainAll(Collection<?> c)406     boolean retainAll(Collection<?> c);
407 
408     /**
409      * Replaces each element of this list with the result of applying the
410      * operator to that element.  Errors or runtime exceptions thrown by
411      * the operator are relayed to the caller.
412      *
413      * @implSpec
414      * The default implementation is equivalent to, for this {@code list}:
415      * <pre>{@code
416      *     final ListIterator<E> li = list.listIterator();
417      *     while (li.hasNext()) {
418      *         li.set(operator.apply(li.next()));
419      *     }
420      * }</pre>
421      *
422      * If the list's list-iterator does not support the {@code set} operation
423      * then an {@code UnsupportedOperationException} will be thrown when
424      * replacing the first element.
425      *
426      * @param operator the operator to apply to each element
427      * @throws UnsupportedOperationException if this list is unmodifiable.
428      *         Implementations may throw this exception if an element
429      *         cannot be replaced or if, in general, modification is not
430      *         supported
431      * @throws NullPointerException if the specified operator is null or
432      *         if the operator result is a null value and this list does
433      *         not permit null elements
434      *         (<a href="Collection.html#optional-restrictions">optional</a>)
435      * @since 1.8
436      */
replaceAll(UnaryOperator<E> operator)437     default void replaceAll(UnaryOperator<E> operator) {
438         Objects.requireNonNull(operator);
439         final ListIterator<E> li = this.listIterator();
440         while (li.hasNext()) {
441             li.set(operator.apply(li.next()));
442         }
443     }
444 
445     // Android-added: List.sort() vs. Collections.sort() app compat.
446     // Added a warning in the documentation.
447     // Collections.sort() calls List.sort() for apps targeting API version >= 26
448     // (Android Oreo) but the other way around for app targeting <= 25 (Nougat).
449     /**
450      * Sorts this list according to the order induced by the specified
451      * {@link Comparator}.
452      *
453      * <p>All elements in this list must be <i>mutually comparable</i> using the
454      * specified comparator (that is, {@code c.compare(e1, e2)} must not throw
455      * a {@code ClassCastException} for any elements {@code e1} and {@code e2}
456      * in the list).
457      *
458      * <p>If the specified comparator is {@code null} then all elements in this
459      * list must implement the {@link Comparable} interface and the elements'
460      * {@linkplain Comparable natural ordering} should be used.
461      *
462      * <p>This list must be modifiable, but need not be resizable.
463      *
464      * <p>For apps running on and targeting Android versions greater than
465      * Nougat (API level {@code > 25}), {@link Collections#sort(List)}
466      * delegates to this method. Such apps must not call
467      * {@link Collections#sort(List)} from this method. Instead, prefer
468      * not overriding this method at all. If you must override it, consider
469      * this implementation:
470      * <pre>
471      * &#064;Override
472      * public void sort(Comparator&lt;? super E&gt; c) {
473      *   Object[] elements = toArray();
474      *   Arrays.sort(elements, c);
475      *   ListIterator&lt;E&gt; iterator = (ListIterator&lt;Object&gt;) listIterator();
476      *   for (Object element : elements) {
477      *     iterator.next();
478      *     iterator.set((E) element);
479      *   }
480      * }
481      * </pre>
482      *
483      * @implSpec
484      * The default implementation obtains an array containing all elements in
485      * this list, sorts the array, and iterates over this list resetting each
486      * element from the corresponding position in the array. (This avoids the
487      * n<sup>2</sup> log(n) performance that would result from attempting
488      * to sort a linked list in place.)
489      *
490      * @implNote
491      * This implementation is a stable, adaptive, iterative mergesort that
492      * requires far fewer than n lg(n) comparisons when the input array is
493      * partially sorted, while offering the performance of a traditional
494      * mergesort when the input array is randomly ordered.  If the input array
495      * is nearly sorted, the implementation requires approximately n
496      * comparisons.  Temporary storage requirements vary from a small constant
497      * for nearly sorted input arrays to n/2 object references for randomly
498      * ordered input arrays.
499      *
500      * <p>The implementation takes equal advantage of ascending and
501      * descending order in its input array, and can take advantage of
502      * ascending and descending order in different parts of the same
503      * input array.  It is well-suited to merging two or more sorted arrays:
504      * simply concatenate the arrays and sort the resulting array.
505      *
506      * <p>The implementation was adapted from Tim Peters's list sort for Python
507      * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
508      * TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic
509      * Sorting and Information Theoretic Complexity", in Proceedings of the
510      * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
511      * January 1993.
512      *
513      * @param c the {@code Comparator} used to compare list elements.
514      *          A {@code null} value indicates that the elements'
515      *          {@linkplain Comparable natural ordering} should be used
516      * @throws ClassCastException if the list contains elements that are not
517      *         <i>mutually comparable</i> using the specified comparator
518      * @throws UnsupportedOperationException if the list's list-iterator does
519      *         not support the {@code set} operation
520      * @throws IllegalArgumentException
521      *         (<a href="Collection.html#optional-restrictions">optional</a>)
522      *         if the comparator is found to violate the {@link Comparator}
523      *         contract
524      * @since 1.8
525      */
526     @SuppressWarnings({"unchecked", "rawtypes"})
sort(Comparator<? super E> c)527     default void sort(Comparator<? super E> c) {
528         Object[] a = this.toArray();
529         Arrays.sort(a, (Comparator) c);
530         ListIterator<E> i = this.listIterator();
531         for (Object e : a) {
532             i.next();
533             i.set((E) e);
534         }
535     }
536 
537     /**
538      * Removes all of the elements from this list (optional operation).
539      * The list will be empty after this call returns.
540      *
541      * @throws UnsupportedOperationException if the {@code clear} operation
542      *         is not supported by this list
543      */
clear()544     void clear();
545 
546 
547     // Comparison and hashing
548 
549     /**
550      * Compares the specified object with this list for equality.  Returns
551      * {@code true} if and only if the specified object is also a list, both
552      * lists have the same size, and all corresponding pairs of elements in
553      * the two lists are <i>equal</i>.  (Two elements {@code e1} and
554      * {@code e2} are <i>equal</i> if {@code Objects.equals(e1, e2)}.)
555      * In other words, two lists are defined to be
556      * equal if they contain the same elements in the same order.  This
557      * definition ensures that the equals method works properly across
558      * different implementations of the {@code List} interface.
559      *
560      * @param o the object to be compared for equality with this list
561      * @return {@code true} if the specified object is equal to this list
562      */
equals(Object o)563     boolean equals(Object o);
564 
565     /**
566      * Returns the hash code value for this list.  The hash code of a list
567      * is defined to be the result of the following calculation:
568      * <pre>{@code
569      *     int hashCode = 1;
570      *     for (E e : list)
571      *         hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
572      * }</pre>
573      * This ensures that {@code list1.equals(list2)} implies that
574      * {@code list1.hashCode()==list2.hashCode()} for any two lists,
575      * {@code list1} and {@code list2}, as required by the general
576      * contract of {@link Object#hashCode}.
577      *
578      * @return the hash code value for this list
579      * @see Object#equals(Object)
580      * @see #equals(Object)
581      */
hashCode()582     int hashCode();
583 
584 
585     // Positional Access Operations
586 
587     /**
588      * Returns the element at the specified position in this list.
589      *
590      * @param index index of the element to return
591      * @return the element at the specified position in this list
592      * @throws IndexOutOfBoundsException if the index is out of range
593      *         ({@code index < 0 || index >= size()})
594      */
get(int index)595     E get(int index);
596 
597     /**
598      * Replaces the element at the specified position in this list with the
599      * specified element (optional operation).
600      *
601      * @param index index of the element to replace
602      * @param element element to be stored at the specified position
603      * @return the element previously at the specified position
604      * @throws UnsupportedOperationException if the {@code set} operation
605      *         is not supported by this list
606      * @throws ClassCastException if the class of the specified element
607      *         prevents it from being added to this list
608      * @throws NullPointerException if the specified element is null and
609      *         this list does not permit null elements
610      * @throws IllegalArgumentException if some property of the specified
611      *         element prevents it from being added to this list
612      * @throws IndexOutOfBoundsException if the index is out of range
613      *         ({@code index < 0 || index >= size()})
614      */
set(int index, E element)615     E set(int index, E element);
616 
617     /**
618      * Inserts the specified element at the specified position in this list
619      * (optional operation).  Shifts the element currently at that position
620      * (if any) and any subsequent elements to the right (adds one to their
621      * indices).
622      *
623      * @param index index at which the specified element is to be inserted
624      * @param element element to be inserted
625      * @throws UnsupportedOperationException if the {@code add} operation
626      *         is not supported by this list
627      * @throws ClassCastException if the class of the specified element
628      *         prevents it from being added to this list
629      * @throws NullPointerException if the specified element is null and
630      *         this list does not permit null elements
631      * @throws IllegalArgumentException if some property of the specified
632      *         element prevents it from being added to this list
633      * @throws IndexOutOfBoundsException if the index is out of range
634      *         ({@code index < 0 || index > size()})
635      */
add(int index, E element)636     void add(int index, E element);
637 
638     /**
639      * Removes the element at the specified position in this list (optional
640      * operation).  Shifts any subsequent elements to the left (subtracts one
641      * from their indices).  Returns the element that was removed from the
642      * list.
643      *
644      * @param index the index of the element to be removed
645      * @return the element previously at the specified position
646      * @throws UnsupportedOperationException if the {@code remove} operation
647      *         is not supported by this list
648      * @throws IndexOutOfBoundsException if the index is out of range
649      *         ({@code index < 0 || index >= size()})
650      */
remove(int index)651     E remove(int index);
652 
653 
654     // Search Operations
655 
656     /**
657      * Returns the index of the first occurrence of the specified element
658      * in this list, or -1 if this list does not contain the element.
659      * More formally, returns the lowest index {@code i} such that
660      * {@code Objects.equals(o, get(i))},
661      * or -1 if there is no such index.
662      *
663      * @param o element to search for
664      * @return the index of the first occurrence of the specified element in
665      *         this list, or -1 if this list does not contain the element
666      * @throws ClassCastException if the type of the specified element
667      *         is incompatible with this list
668      *         (<a href="Collection.html#optional-restrictions">optional</a>)
669      * @throws NullPointerException if the specified element is null and this
670      *         list does not permit null elements
671      *         (<a href="Collection.html#optional-restrictions">optional</a>)
672      */
indexOf(Object o)673     int indexOf(Object o);
674 
675     /**
676      * Returns the index of the last occurrence of the specified element
677      * in this list, or -1 if this list does not contain the element.
678      * More formally, returns the highest index {@code i} such that
679      * {@code Objects.equals(o, get(i))},
680      * or -1 if there is no such index.
681      *
682      * @param o element to search for
683      * @return the index of the last occurrence of the specified element in
684      *         this list, or -1 if this list does not contain the element
685      * @throws ClassCastException if the type of the specified element
686      *         is incompatible with this list
687      *         (<a href="Collection.html#optional-restrictions">optional</a>)
688      * @throws NullPointerException if the specified element is null and this
689      *         list does not permit null elements
690      *         (<a href="Collection.html#optional-restrictions">optional</a>)
691      */
lastIndexOf(Object o)692     int lastIndexOf(Object o);
693 
694 
695     // List Iterators
696 
697     /**
698      * Returns a list iterator over the elements in this list (in proper
699      * sequence).
700      *
701      * @return a list iterator over the elements in this list (in proper
702      *         sequence)
703      */
listIterator()704     ListIterator<E> listIterator();
705 
706     /**
707      * Returns a list iterator over the elements in this list (in proper
708      * sequence), starting at the specified position in the list.
709      * The specified index indicates the first element that would be
710      * returned by an initial call to {@link ListIterator#next next}.
711      * An initial call to {@link ListIterator#previous previous} would
712      * return the element with the specified index minus one.
713      *
714      * @param index index of the first element to be returned from the
715      *        list iterator (by a call to {@link ListIterator#next next})
716      * @return a list iterator over the elements in this list (in proper
717      *         sequence), starting at the specified position in the list
718      * @throws IndexOutOfBoundsException if the index is out of range
719      *         ({@code index < 0 || index > size()})
720      */
listIterator(int index)721     ListIterator<E> listIterator(int index);
722 
723     // View
724 
725     /**
726      * Returns a view of the portion of this list between the specified
727      * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.  (If
728      * {@code fromIndex} and {@code toIndex} are equal, the returned list is
729      * empty.)  The returned list is backed by this list, so non-structural
730      * changes in the returned list are reflected in this list, and vice-versa.
731      * The returned list supports all of the optional list operations supported
732      * by this list.<p>
733      *
734      * This method eliminates the need for explicit range operations (of
735      * the sort that commonly exist for arrays).  Any operation that expects
736      * a list can be used as a range operation by passing a subList view
737      * instead of a whole list.  For example, the following idiom
738      * removes a range of elements from a list:
739      * <pre>{@code
740      *      list.subList(from, to).clear();
741      * }</pre>
742      * Similar idioms may be constructed for {@code indexOf} and
743      * {@code lastIndexOf}, and all of the algorithms in the
744      * {@code Collections} class can be applied to a subList.<p>
745      *
746      * The semantics of the list returned by this method become undefined if
747      * the backing list (i.e., this list) is <i>structurally modified</i> in
748      * any way other than via the returned list.  (Structural modifications are
749      * those that change the size of this list, or otherwise perturb it in such
750      * a fashion that iterations in progress may yield incorrect results.)
751      *
752      * @param fromIndex low endpoint (inclusive) of the subList
753      * @param toIndex high endpoint (exclusive) of the subList
754      * @return a view of the specified range within this list
755      * @throws IndexOutOfBoundsException for an illegal endpoint index value
756      *         ({@code fromIndex < 0 || toIndex > size ||
757      *         fromIndex > toIndex})
758      */
subList(int fromIndex, int toIndex)759     List<E> subList(int fromIndex, int toIndex);
760 
761     /**
762      * Creates a {@link Spliterator} over the elements in this list.
763      *
764      * <p>The {@code Spliterator} reports {@link Spliterator#SIZED} and
765      * {@link Spliterator#ORDERED}.  Implementations should document the
766      * reporting of additional characteristic values.
767      *
768      * @implSpec
769      * The default implementation creates a
770      * <em><a href="Spliterator.html#binding">late-binding</a></em>
771      * spliterator as follows:
772      * <ul>
773      * <li>If the list is an instance of {@link RandomAccess} then the default
774      *     implementation creates a spliterator that traverses elements by
775      *     invoking the method {@link List#get}.  If such invocation results or
776      *     would result in an {@code IndexOutOfBoundsException} then the
777      *     spliterator will <em>fail-fast</em> and throw a
778      *     {@code ConcurrentModificationException}.
779      *     If the list is also an instance of {@link AbstractList} then the
780      *     spliterator will use the list's {@link AbstractList#modCount modCount}
781      *     field to provide additional <em>fail-fast</em> behavior.
782      * <li>Otherwise, the default implementation creates a spliterator from the
783      *     list's {@code Iterator}.  The spliterator inherits the
784      *     <em>fail-fast</em> of the list's iterator.
785      * </ul>
786      *
787      * @implNote
788      * The created {@code Spliterator} additionally reports
789      * {@link Spliterator#SUBSIZED}.
790      *
791      * @return a {@code Spliterator} over the elements in this list
792      * @since 1.8
793      */
794     @Override
spliterator()795     default Spliterator<E> spliterator() {
796         if (this instanceof RandomAccess) {
797             return new AbstractList.RandomAccessSpliterator<>(this);
798         } else {
799             return Spliterators.spliterator(this, Spliterator.ORDERED);
800         }
801     }
802 
803     /**
804      * Returns an unmodifiable list containing zero elements.
805      *
806      * See <a href="#unmodifiable">Unmodifiable Lists</a> for details.
807      *
808      * @param <E> the {@code List}'s element type
809      * @return an empty {@code List}
810      *
811      * @since 9
812      */
813     @SuppressWarnings("unchecked")
of()814     static <E> List<E> of() {
815         return (List<E>) ImmutableCollections.EMPTY_LIST;
816     }
817 
818     /**
819      * Returns an unmodifiable list containing one element.
820      *
821      * See <a href="#unmodifiable">Unmodifiable Lists</a> for details.
822      *
823      * @param <E> the {@code List}'s element type
824      * @param e1 the single element
825      * @return a {@code List} containing the specified element
826      * @throws NullPointerException if the element is {@code null}
827      *
828      * @since 9
829      */
of(E e1)830     static <E> List<E> of(E e1) {
831         return new ImmutableCollections.List12<>(e1);
832     }
833 
834     /**
835      * Returns an unmodifiable list containing two elements.
836      *
837      * See <a href="#unmodifiable">Unmodifiable Lists</a> for details.
838      *
839      * @param <E> the {@code List}'s element type
840      * @param e1 the first element
841      * @param e2 the second element
842      * @return a {@code List} containing the specified elements
843      * @throws NullPointerException if an element is {@code null}
844      *
845      * @since 9
846      */
of(E e1, E e2)847     static <E> List<E> of(E e1, E e2) {
848         return new ImmutableCollections.List12<>(e1, e2);
849     }
850 
851     /**
852      * Returns an unmodifiable list containing three elements.
853      *
854      * See <a href="#unmodifiable">Unmodifiable Lists</a> for details.
855      *
856      * @param <E> the {@code List}'s element type
857      * @param e1 the first element
858      * @param e2 the second element
859      * @param e3 the third element
860      * @return a {@code List} containing the specified elements
861      * @throws NullPointerException if an element is {@code null}
862      *
863      * @since 9
864      */
of(E e1, E e2, E e3)865     static <E> List<E> of(E e1, E e2, E e3) {
866         return ImmutableCollections.listFromTrustedArray(e1, e2, e3);
867     }
868 
869     /**
870      * Returns an unmodifiable list containing four elements.
871      *
872      * See <a href="#unmodifiable">Unmodifiable Lists</a> for details.
873      *
874      * @param <E> the {@code List}'s element type
875      * @param e1 the first element
876      * @param e2 the second element
877      * @param e3 the third element
878      * @param e4 the fourth element
879      * @return a {@code List} containing the specified elements
880      * @throws NullPointerException if an element is {@code null}
881      *
882      * @since 9
883      */
of(E e1, E e2, E e3, E e4)884     static <E> List<E> of(E e1, E e2, E e3, E e4) {
885         return ImmutableCollections.listFromTrustedArray(e1, e2, e3, e4);
886     }
887 
888     /**
889      * Returns an unmodifiable list containing five elements.
890      *
891      * See <a href="#unmodifiable">Unmodifiable Lists</a> for details.
892      *
893      * @param <E> the {@code List}'s element type
894      * @param e1 the first element
895      * @param e2 the second element
896      * @param e3 the third element
897      * @param e4 the fourth element
898      * @param e5 the fifth element
899      * @return a {@code List} containing the specified elements
900      * @throws NullPointerException if an element is {@code null}
901      *
902      * @since 9
903      */
of(E e1, E e2, E e3, E e4, E e5)904     static <E> List<E> of(E e1, E e2, E e3, E e4, E e5) {
905         return ImmutableCollections.listFromTrustedArray(e1, e2, e3, e4, e5);
906     }
907 
908     /**
909      * Returns an unmodifiable list containing six elements.
910      *
911      * See <a href="#unmodifiable">Unmodifiable Lists</a> for details.
912      *
913      * @param <E> the {@code List}'s element type
914      * @param e1 the first element
915      * @param e2 the second element
916      * @param e3 the third element
917      * @param e4 the fourth element
918      * @param e5 the fifth element
919      * @param e6 the sixth element
920      * @return a {@code List} containing the specified elements
921      * @throws NullPointerException if an element is {@code null}
922      *
923      * @since 9
924      */
of(E e1, E e2, E e3, E e4, E e5, E e6)925     static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6) {
926         return ImmutableCollections.listFromTrustedArray(e1, e2, e3, e4, e5,
927                                                          e6);
928     }
929 
930     /**
931      * Returns an unmodifiable list containing seven elements.
932      *
933      * See <a href="#unmodifiable">Unmodifiable Lists</a> for details.
934      *
935      * @param <E> the {@code List}'s element type
936      * @param e1 the first element
937      * @param e2 the second element
938      * @param e3 the third element
939      * @param e4 the fourth element
940      * @param e5 the fifth element
941      * @param e6 the sixth element
942      * @param e7 the seventh element
943      * @return a {@code List} containing the specified elements
944      * @throws NullPointerException if an element is {@code null}
945      *
946      * @since 9
947      */
of(E e1, E e2, E e3, E e4, E e5, E e6, E e7)948     static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7) {
949         return ImmutableCollections.listFromTrustedArray(e1, e2, e3, e4, e5,
950                                                          e6, e7);
951     }
952 
953     /**
954      * Returns an unmodifiable list containing eight elements.
955      *
956      * See <a href="#unmodifiable">Unmodifiable Lists</a> for details.
957      *
958      * @param <E> the {@code List}'s element type
959      * @param e1 the first element
960      * @param e2 the second element
961      * @param e3 the third element
962      * @param e4 the fourth element
963      * @param e5 the fifth element
964      * @param e6 the sixth element
965      * @param e7 the seventh element
966      * @param e8 the eighth element
967      * @return a {@code List} containing the specified elements
968      * @throws NullPointerException if an element is {@code null}
969      *
970      * @since 9
971      */
of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8)972     static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) {
973         return ImmutableCollections.listFromTrustedArray(e1, e2, e3, e4, e5,
974                                                          e6, e7, e8);
975     }
976 
977     /**
978      * Returns an unmodifiable list containing nine elements.
979      *
980      * See <a href="#unmodifiable">Unmodifiable Lists</a> for details.
981      *
982      * @param <E> the {@code List}'s element type
983      * @param e1 the first element
984      * @param e2 the second element
985      * @param e3 the third element
986      * @param e4 the fourth element
987      * @param e5 the fifth element
988      * @param e6 the sixth element
989      * @param e7 the seventh element
990      * @param e8 the eighth element
991      * @param e9 the ninth element
992      * @return a {@code List} containing the specified elements
993      * @throws NullPointerException if an element is {@code null}
994      *
995      * @since 9
996      */
of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9)997     static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) {
998         return ImmutableCollections.listFromTrustedArray(e1, e2, e3, e4, e5,
999                                                          e6, e7, e8, e9);
1000     }
1001 
1002     /**
1003      * Returns an unmodifiable list containing ten elements.
1004      *
1005      * See <a href="#unmodifiable">Unmodifiable Lists</a> for details.
1006      *
1007      * @param <E> the {@code List}'s element type
1008      * @param e1 the first element
1009      * @param e2 the second element
1010      * @param e3 the third element
1011      * @param e4 the fourth element
1012      * @param e5 the fifth element
1013      * @param e6 the sixth element
1014      * @param e7 the seventh element
1015      * @param e8 the eighth element
1016      * @param e9 the ninth element
1017      * @param e10 the tenth element
1018      * @return a {@code List} containing the specified elements
1019      * @throws NullPointerException if an element is {@code null}
1020      *
1021      * @since 9
1022      */
of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)1023     static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) {
1024         return ImmutableCollections.listFromTrustedArray(e1, e2, e3, e4, e5,
1025                                                          e6, e7, e8, e9, e10);
1026     }
1027 
1028     /**
1029      * Returns an unmodifiable list containing an arbitrary number of elements.
1030      * See <a href="#unmodifiable">Unmodifiable Lists</a> for details.
1031      *
1032      * @apiNote
1033      * This method also accepts a single array as an argument. The element type of
1034      * the resulting list will be the component type of the array, and the size of
1035      * the list will be equal to the length of the array. To create a list with
1036      * a single element that is an array, do the following:
1037      *
1038      * <pre>{@code
1039      *     String[] array = ... ;
1040      *     List<String[]> list = List.<String[]>of(array);
1041      * }</pre>
1042      *
1043      * This will cause the {@link List#of(Object) List.of(E)} method
1044      * to be invoked instead.
1045      *
1046      * @param <E> the {@code List}'s element type
1047      * @param elements the elements to be contained in the list
1048      * @return a {@code List} containing the specified elements
1049      * @throws NullPointerException if an element is {@code null} or if the array is {@code null}
1050      *
1051      * @since 9
1052      */
1053     @SafeVarargs
1054     @SuppressWarnings("varargs")
of(E... elements)1055     static <E> List<E> of(E... elements) {
1056         switch (elements.length) { // implicit null check of elements
1057             case 0:
1058                 @SuppressWarnings("unchecked")
1059                 var list = (List<E>) ImmutableCollections.EMPTY_LIST;
1060                 return list;
1061             case 1:
1062                 return new ImmutableCollections.List12<>(elements[0]);
1063             case 2:
1064                 return new ImmutableCollections.List12<>(elements[0], elements[1]);
1065             default:
1066                 return ImmutableCollections.listFromArray(elements);
1067         }
1068     }
1069 
1070     /**
1071      * Returns an <a href="#unmodifiable">unmodifiable List</a> containing the elements of
1072      * the given Collection, in its iteration order. The given Collection must not be null,
1073      * and it must not contain any null elements. If the given Collection is subsequently
1074      * modified, the returned List will not reflect such modifications.
1075      *
1076      * @implNote
1077      * If the given Collection is an <a href="#unmodifiable">unmodifiable List</a>,
1078      * calling copyOf will generally not create a copy.
1079      *
1080      * @param <E> the {@code List}'s element type
1081      * @param coll a {@code Collection} from which elements are drawn, must be non-null
1082      * @return a {@code List} containing the elements of the given {@code Collection}
1083      * @throws NullPointerException if coll is null, or if it contains any nulls
1084      * @since 10
1085      */
copyOf(Collection<? extends E> coll)1086     static <E> List<E> copyOf(Collection<? extends E> coll) {
1087         return ImmutableCollections.listCopy(coll);
1088     }
1089 }
1090