欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java源码——List接口

程序员文章站 2022-03-15 15:24:32
Java源码——...

Java源码——List接口

接口官方注释(源码注释)

这些官方注释可以再源码中看也可以在 jdk8的在线文档 中找到。
Java源码——List接口

先来简单看看官方的解释说明:

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
List 指的是一个有序集合(也称为序列)。给接口的使用者可以精确控制列表中每个元素的插入位置。使用者可以通过其整数索引(在列表中的位置)访问元素,以及在列表中搜索元素。

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.
序列(List)与集合(Set)不同,列表通常允许重复的元素。更正式地说,列表通常允许元素e1和e2重复,例如e1.equals(e2),如果列表允许null元素,则通常允许有多个null元素。当用户尝试插入运行时异常时,有人可能希望通过抛出运行时异常来实现禁止重复的列表,这并非不可想象的,但我们预计这种使用很少。

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.
List接口对iterator()、add()、remove()、equals()和hashCode()方法做了额外的规定,而不是Collection 集合接口中指定的那些。为了方便起见,这里还包括了其他继承方法的声明。

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.
List接口提供了四种对列表元素进行位置(索引)访问的方法。列表的索引(比如Java数组)是从零开始的。请注意,对于某些实现(例如LinkedList类),这些操作的执行时间可能与索引值成比例。因此,在调用方不知道具体实现的情况下,迭代列表中的元素通常比索引列表中的元素更好。

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.
List接口提供了一个特殊的迭代器,称为ListIterator,除了迭代器接口提供的常规操作之外,还允许元素插入和替换,以及双向访问。提供了一个方法来获取从列表中指定位置开始的列表迭代器。

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.
List接口提供了两种方法来搜索指定的对象。从性能的角度来看,应该谨慎使用这些方法。在许多实现中,它们将执行代价高昂的线性搜索

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.
List接口提供了两种方法来有效地在列表中的任意点插入和删除多个元素

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.
注意:虽然允许列表将其自身作为元素包含,但还是要格外小心:equals和hashCode方法在这样的列表中已经没有很好的定义了。

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as “optional” in the specification for this interface.
有些列表实现类对它们可能包含的元素有限制。例如,有些实现类禁止空元素,有些实现类对其元素的类型有限制。尝试添加不合格的元素会引发未经检查的异常,通常为NullPointerException或ClassCastException。尝试查询不合格元素的存在可能会引发异常,也可能只是返回false;有些实现类将显示前一种行为,有些实现类将显示后一种行为。更一般地说,尝试对一个不合格的元素执行操作,而该元素的完成不会导致将不合格元素插入列表中,则可能会引发异常,也可能会成功,具体取决于实现。此类异常在该接口的规范中标记为“可选”。

This interface is a member of the Java Collections Framework.
此接口是Java集合框架的一个成员。

对比Collection和List的方法

public interface List<E> extends Collection<E> 

List 的意思是 序列,列表,List是Java集合框架的一个成员。在之前的文章中我了解了AbstractCollection抽象类,它是Collection接口的一个基础实现,为了让开发者能更简便的实现一个集合类,所以它给出了一些方法的基本实现,在不追求更高性能的情况下可以不用重写这些方法(可以少写不少代码)。然而,List 接口只是继承了Collection接口,所以他的方法大多数也没有具体的实现。如果说Collection接口定义集合类的规范,那么 List 接口可以看作是一个特殊集合(即列表实现类)的新规范(当然也是集合,之后还会又Set,Queue)。下面通过表格看看List接口在Collection接口之上又做了那些变化:

其中加粗表示提供了实现,– 表示当前接口/类中不存在这个方法。

Collection 与 List 中的方法对比列表:

Collection AbstractCollection
int size(); int size();
boolean isEmpty(); boolean isEmpty()
boolean contains(Object o); boolean contains(Object o)
Iterator< E > iterator(); Iterator< E > iterator()
Object[] toArray(); Object [ ] toArray()
< T > T[] toArray(T[] a); < T > T[ ] toArray(T[] a);
boolean add(E e); boolean add(E e)
boolean remove(Object o); boolean remove(Object o)
boolean containsAll(Collection<?> c); boolean containsAll(Collection<?> c)
boolean addAll(Collection<? extends E> c); boolean addAll(Collection<? extends E> c);
- boolean addAll(int index, Collection<? extends E> c);
boolean removeAll(Collection<?> c); boolean removeAll(Collection<?> c);
default boolean removeIf(Predicate< ? super E > filter) -
boolean retainAll(Collection<?> c); boolean retainAll(Collection<?> c);
- default void replaceAll(UnaryOperator< E > operator)
- default void sort(Comparator< ? super E > c)
void clear(); void clear();
boolean equals(Object o); boolean equals(Object o);
int hashCode(); int hashCode();
- E get(int index);
- E set(int index, E element);
- void add(int index, E element);
- E remove(int index);
- int indexOf(Object o);
- int lastIndexOf(Object o);
- ListIterator< E > listIterator();
- ListIterator< E > listIterator(int index);
- List< E > subList(int fromIndex, int toIndex);
default Spliterator< E > spliterator() default Spliterator< E > spliterator()
default Stream< E > stream() -
default Stream< E > parallelStream() -

从上面的表中可以看出,List接口继承了Colloction接口并覆盖了它大部分的方法,除此之外List接口还围绕索引(index)这个概念新增了很多方法,这一点与官方注释相应征。

主要方法详细价绍

这里主要看有具体实现的方法和新增的方法,因为其他都是覆盖Collection的方法,含义与之前Collection接口以及AbstractCollection抽象类中提到的类似,就不做多余的解释了,等遇到具体实现(例如AbstractList,ArrayList中)时在详细说明。

replaceAll方法

    /**
     * Replaces each element of this list with the result of applying the
     * operator to that element.  Errors or runtime exceptions thrown by
     * the operator are relayed to the caller.
     *
     * @implSpec
     * The default implementation is equivalent to, for this {@code list}:
     * <pre>{@code
     *     final ListIterator<E> li = list.listIterator();
     *     while (li.hasNext()) {
     *         li.set(operator.apply(li.next()));
     *     }
     * }</pre>
     *
     * If the list's list-iterator does not support the {@code set} operation
     * then an {@code UnsupportedOperationException} will be thrown when
     * replacing the first element.
     *
     * @param operator the operator to apply to each element
     * @throws UnsupportedOperationException if this list is unmodifiable.
     *         Implementations may throw this exception if an element
     *         cannot be replaced or if, in general, modification is not
     *         supported
     * @throws NullPointerException if the specified operator is null or
     *         if the operator result is a null value and this list does
     *         not permit null elements
     *         (<a href="Collection.html#optional-restrictions">optional</a>)
     * @since 1.8
     */
    default void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final ListIterator<E> li = this.listIterator();
        while (li.hasNext()) {
            li.set(operator.apply(li.next()));
        }
    }

sort方法

    /**
     * Sorts this list according to the order induced by the specified
     * {@link Comparator}.
     *
     * <p>All elements in this list must be <i>mutually comparable</i> using the
     * specified comparator (that is, {@code c.compare(e1, e2)} must not throw
     * a {@code ClassCastException} for any elements {@code e1} and {@code e2}
     * in the list).
     *
     * <p>If the specified comparator is {@code null} then all elements in this
     * list must implement the {@link Comparable} interface and the elements'
     * {@linkplain Comparable natural ordering} should be used.
     *
     * <p>This list must be modifiable, but need not be resizable.
     *
     * @implSpec
     * The default implementation obtains an array containing all elements in
     * this list, sorts the array, and iterates over this list resetting each
     * element from the corresponding position in the array. (This avoids the
     * n<sup>2</sup> log(n) performance that would result from attempting
     * to sort a linked list in place.)
     *
     * @implNote
     * This implementation is a stable, adaptive, iterative mergesort that
     * requires far fewer than n lg(n) comparisons when the input array is
     * partially sorted, while offering the performance of a traditional
     * mergesort when the input array is randomly ordered.  If the input array
     * is nearly sorted, the implementation requires approximately n
     * comparisons.  Temporary storage requirements vary from a small constant
     * for nearly sorted input arrays to n/2 object references for randomly
     * ordered input arrays.
     *
     * <p>The implementation takes equal advantage of ascending and
     * descending order in its input array, and can take advantage of
     * ascending and descending order in different parts of the same
     * input array.  It is well-suited to merging two or more sorted arrays:
     * simply concatenate the arrays and sort the resulting array.
     *
     * <p>The implementation was adapted from Tim Peters's list sort for Python
     * (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
     * TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic
     * Sorting and Information Theoretic Complexity", in Proceedings of the
     * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
     * January 1993.
     *
     * @param c the {@code Comparator} used to compare list elements.
     *          A {@code null} value indicates that the elements'
     *          {@linkplain Comparable natural ordering} should be used
     * @throws ClassCastException if the list contains elements that are not
     *         <i>mutually comparable</i> using the specified comparator
     * @throws UnsupportedOperationException if the list's list-iterator does
     *         not support the {@code set} operation
     * @throws IllegalArgumentException
     *         (<a href="Collection.html#optional-restrictions">optional</a>)
     *         if the comparator is found to violate the {@link Comparator}
     *         contract
     * @since 1.8
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    default void sort(Comparator<? super E> c) {
        Object[] a = this.toArray();
        Arrays.sort(a, (Comparator) c);
        ListIterator<E> i = this.listIterator();
        for (Object e : a) {
            i.next();
            i.set((E) e);
        }
    }

集合框架全景图:
Java源码——List接口

本文地址:https://blog.csdn.net/qq_33471737/article/details/109189125