Data Structure - List Interface

Brief introduction

List interface inherited from the Collection interface, is one of three interfaces extend Collection. List the elements are ordered, and support with the index visit. List of elements simultaneously allows duplicate.

public interface List<E> extends Collection<E>
method

List of most of the Collection interface method has redefined again, of course, define your own unique way, it is important to speak here unique method, other method please refer to an interface Collection.

// 替换所有 UnaryOperator会另开一篇讲解
default void replaceAll(UnaryOperator<E> operator) {
    Objects.requireNonNull(operator);
    final ListIterator<E> li = this.listIterator();
    while (li.hasNext()) {
        li.set(operator.apply(li.next()));
    }
}
// 排序
@SuppressWarnings({"unchecked", "rawtypes"})
default void sort(Comparator<? super E> c) {
    Object[] a = this.toArray();
    // 主要使用 Arrays.sort 进行排序
    Arrays.sort(a, (Comparator) c);
    // 迭代原集合
    ListIterator<E> i = this.listIterator();
    // 遍历新数组
    for (Object e : a) {
        i.next();
        // 使原集合中元素位置跟新数组中一致,这里直接替换
        i.set((E) e);
    }
}
// 根据索引查找
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);

With respect for the Collection interface, List interface adds a lot of index operations, and not only to provide general Iterator iterator and provides ListIterator list iterator, bidirectional operation more convenient

AbstractList abstract class

AbstractList implement the List interface, we can see from the name of the class is an abstract class that provides a list of some of the basic realization of the class action.

public abstract class AbstractList<E> 
        extends AbstractCollection<E> implements List<E>
Constructor
protected AbstractList() {
}
Attributes
// 修改次数
protected transient int modCount = 0;
The method is not implemented
abstract public E get(int index);
The method has been implemented

In only a few AbstractList method is not overridden by a subclass (e.g., equals, hashCode), most methods are overridden by subclasses

Add to
public boolean add(E e) {
    add(size(), e);
    return true;
}
​
public void add(int index, E element) {
    throw new UnsupportedOperationException();
}
​
public boolean addAll(int index, Collection<? extends E> c) {
    // 是否越界校验
    rangeCheckForAdd(index);
    boolean modified = false;
    for (E e : c) {
        add(index++, e);
        modified = true;
    }
    return modified;
}
​
private void rangeCheckForAdd(int index) {
    if (index < 0 || index > size())
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

add (E e) calls add (int index, E element), a direct call attention will throw exception, Subclasses must override this method

Set value
public E set(int index, E element) {
    throw new UnsupportedOperationException();
}

Also note that direct call to throw an exception, subclass must override this method

delete
public E remove(int index) {
    throw new UnsupportedOperationException();
}
​
protected void removeRange(int fromIndex, int toIndex) {
    // 按起始位置构建列表迭代器
    ListIterator<E> it = listIterator(fromIndex);
    // 遍历范围内的所有元素
    for (int i=0, n=toIndex-fromIndex; i<n; i++) {
        // 迭代删除
        it.next();
        it.remove();
    }
}

Directly call remove (int index) will throw an exception, subclass must override this method

Seek
// 获取元素索引
public int indexOf(Object o) {
    // 获取此集合列表迭代器
    ListIterator<E> it = listIterator();
    if (o==null) {
        // 参数为空时找元素为空的索引
        while (it.hasNext())
            // 找到第一个就返回
            if (it.next()==null)
                return it.previousIndex();
    } else {
        // 参数不为空,找元素和参数equals一样的索引
        while (it.hasNext())
            // 找到第一个就返回
            if (o.equals(it.next()))
                return it.previousIndex();
    }
    // 没有找到返回-1
    return -1;
}
​
// 按索引查找
public int lastIndexOf(Object o) {
    // 获取此集合列表迭代器
    ListIterator<E> it = listIterator(size());
    if (o==null) {
        // 参数为空时找元素为空的索引,这里是从最后一个找起
        while (it.hasPrevious())
            // 找到第一个就返回(倒找找第一个,实际上就是最后一个)
            if (it.previous()==null)
                return it.nextIndex();
    } else {
        // 参数不为空,找元素和参数equals一样的索引(倒着找)
        while (it.hasPrevious())
            // 找到第一个就返回(倒找找第一个,实际上就是最后一个)
            if (o.equals(it.previous()))
                return it.nextIndex();
    }
    // 没有找到返回-1
    return -1;
}
Clear
public void clear() {
    // 从第一个元素开始删除
    removeRange(0, size());
}
hashCode method
public int hashCode() {
    // 初始化为1,如果元素为空,hashCode就为1
    int hashCode = 1;
    for (E e : this)
        // 上一次 hashCode 乘以31,加上当前元素的 hashCode
        hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
    // 返回 hashCode
    return hashCode;
}
equals method
public boolean equals(Object o) {
    // 参数与当前集合内存地址一样,返回true
    if (o == this)
        return true;
    // 参数不是List或List子类的实例,返回false
    if (!(o instanceof List))
        return false;
    // 获取两个迭代器
    ListIterator<E> e1 = listIterator();
    ListIterator<?> e2 = ((List<?>) o).listIterator();
    // 同时迭代两个集合,同时有值才可以迭代
    while (e1.hasNext() && e2.hasNext()) {
        // 分别获取元素
        E o1 = e1.next();
        Object o2 = e2.next();
        // 判断两个元素是否一致,都为空或equals一致
        if (!(o1==null ? o2==null : o1.equals(o2)))
            return false;
    }
    // 能到这至少有一个迭代完,有一个没迭代完就返回false
    return !(e1.hasNext() || e2.hasNext());
}
Iterator
// 获取迭代器
public Iterator<E> iterator() {
    return new Itr();
}
// 获取列表迭代器
public ListIterator<E> listIterator() {
    return listIterator(0);
}
// 从某一位置构建迭代器
public ListIterator<E> listIterator(final int index) {
    rangeCheckForAdd(index);
​
    return new ListItr(index);
}
Internal class Itr
private class Itr implements Iterator<E> {
​
    int cursor = 0;
    int lastRet = -1;
    int expectedModCount = modCount;
    
    public boolean hasNext() {...}
    public E next() {...}
    public void remove() {...}
    final void checkForComodification() {...}
}

This inner class is to achieve an Iterator basic functions

Internal class ListItr
private class ListItr extends Itr implements ListIterator<E> {
    ListItr(int index) {...}
    public boolean hasPrevious() {...}
    public E previous() {...}
    public int nextIndex() {...}
    public int previousIndex() {...}
    public void set(E e) {...}
    public void add(E e) {...}
}

This inner class inherits Itr and achieve ListIterator, classic adapter pattern, and extend Itr, it has a two-way iterative function

Outside the SubList
class SubList<E> extends AbstractList<E>

SubList AbstractList class inherits from the abstract class, so its list of examples of various methods AbstractList has been achieved may be used.

External class RandomAccessSubList
class RandomAccessSubList<E> 
        extends SubList<E> implements RandomAccess

RandomAccessSubList class inherits from SubList, and implements RandomAccess interfaces, RandomAccess interface is simply represents an example of such support random access.

Guess you like

Origin www.cnblogs.com/yuanjiangnan/p/12506678.html