JDK源码解析---AbstractList

1.概述

AbstractList是List的抽象实现,

简单实现了一些关于List的基本操作。

2.类图

在这里插入图片描述
继承了AbstractCollection抽象集合类,AbstractCollection是java自己提供的一个最基本的Collection的实现。当然它依然是一个抽象类。

对于一个不可更改的集合,只要继承这个类并且实现迭代器和size()方法就行。

对于一个可更改的集合,需要实现add和返回Iterator的方法,当然可选的实现remove方法

实现了List接口,List接口定义了列表的一些基本的方法

3.构造方法

无参构造方法 由protected修饰,说明是外部无法访问的,子类可以在内部使用此构造函数。

protected AbstractList() {
}

4.基本方法

很多方法中都是直接抛出UnsupportedOperationException()异常

这表明当子类继承这个类但没有实现这个方法,却被调用的这个方法的时候就会抛出异常。

public boolean add(E e) { // 添加方法,内部调用add(int index, E element)
    add(size(), e);
    return true;
}
public void add(int index, E element) { 
    throw new UnsupportedOperationException();
}
    
abstract public E get(int index);//抽象方法,获取指定索引的元素

public E set(int index, E element) {//在某个索引位置设置元素
    throw new UnsupportedOperationException();
}
public E remove(int index) {//异常索引对应的元素
    throw new UnsupportedOperationException();
}

public int indexOf(Object o) {//从前往后找 利用迭代器去寻找指定的元素,返回其位置,没找到的话返回-1
    ListIterator<E> it = listIterator();
    if (o==null) {
       while (it.hasNext())
           if (it.next()==null)
               return it.previousIndex();
    } else {
        while (it.hasNext())
            if (o.equals(it.next()))
                return it.previousIndex();
    }
    return -1;
}

public int lastIndexOf(Object o) {//从后往前找 利用迭代器去寻找指定的元素,返回其位置,没找到的话返回-1
    ListIterator<E> it = listIterator(size());
    if (o==null) {
        while (it.hasPrevious())
            if (it.previous()==null)
               return it.nextIndex();
    } else {
       while (it.hasPrevious())
           if (o.equals(it.previous()))
                return it.nextIndex();
    }
    return -1;
}

public void clear() {//内部调用removeRange(int fromIndex, int toIndex),从0到末尾清除
    removeRange(0, size());
}
protected void removeRange(int fromIndex, int toIndex) {//protected修饰的方法,不能被外部调用,所以是一个内部的抽取出的一个公共方法。从起始位置fromIndex 到 toIndex的元素删除。前闭后开
    ListIterator<E> it = listIterator(fromIndex);
    for (int i=0, n=toIndex-fromIndex; i<n; i++) {
        it.next();
        it.remove();
    }
}

public boolean addAll(int index, Collection<? extends E> c) {//将集合c添加到索引index开始的位置 包括index这一位
    rangeCheckForAdd(index);//判断索引是否越界
    boolean modified = false;
    for (E e : c) {
        add(index++, e);
        modified = true;   
    }
    return modified;
}

public List<E> subList(int fromIndex, int toIndex) {//获得子列表的引用
        return (this instanceof RandomAccess ?
                new RandomAccessSubList<>(this, fromIndex, toIndex):
                new SubList<>(this, fromIndex, toIndex));
    }

5.迭代器

5.1获得迭代器

public Iterator<E> iterator() {
    return new Itr();
}

list迭代器 第一无参的内部调用listIterator(0),返回一个从索引0开始迭代的迭代器

第二个是根据参数 返回从索引index开始迭代的迭代器

public ListIterator<E> listIterator() {
    return listIterator(0);
}

public ListIterator<E> listIterator(final int index) {
        rangeCheckForAdd(index);
        return new ListItr(index);
}

5.2 Itr

实现了Iterator接口 该接口实现了迭代器的基本方法

5.2.1成员变量
int cursor = 0;//游标 当前索引

int lastRet = -1;//上一次操作的索引

int expectedModCount = modCount;// 预期的修改次数,估计是用于CAS吧
5.2.2基本方法
public boolean hasNext() {//判断是否有下一个元素,当前游标不等于大小就说明有下一个元素
    return cursor != size();
}
public E next() {// 获取当前游标元素,并记录这一次操作的位置lastRet 然后游标往后移动一位。返回当前元素。
    checkForComodification();
    try {
        int i = cursor;
        E next = get(i);
        lastRet = i;
        cursor = i + 1;
        return next;
    } catch (IndexOutOfBoundsException e) {
        checkForComodification();
        throw new NoSuchElementException();
    }
}

public void remove() {
    if (lastRet < 0)
        throw new IllegalStateException();
    checkForComodification();

    try {
        AbstractList.this.remove(lastRet);//注意移除的是lastRet所指向的元素
        if (lastRet < cursor)//若比游标小,游标-1
            cursor--;
        lastRet = -1;//lastRet设置成-1。连续两次调用remove则会抛出异常。
        expectedModCount = modCount;
    } catch (IndexOutOfBoundsException e) {
        throw new ConcurrentModificationException();
    }
}
final void checkForComodification() {//检查当前是否可以进行操作。
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
}

5.3 ListItr

继承了Itr 并实现了ListIterator

5.3.1 构造方法

根据参数设置当前游标

ListItr(int index) {
    cursor = index;
}
5.3.2 基本方法
public boolean hasPrevious() {//是否前面有元素
    return cursor != 0;
}
public E previous() {//获取前一个元素 同理也是要记录lastRet
    checkForComodification();
    try {
        int i = cursor - 1;
        E previous = get(i);
        lastRet = cursor = i;
        return previous;
    } catch (IndexOutOfBoundsException e) {
        checkForComodification();
        throw new NoSuchElementException();
    }
}
public int nextIndex() {//获取当前游标
    return cursor;
}
public int previousIndex() {//获取游标前一位索引
    return cursor-1;
}
public void set(E e) {//修改元素
    if (lastRet < 0)
        throw new IllegalStateException();
    checkForComodification();

    try {
        AbstractList.this.set(lastRet, e);//lastRet的元素设置成e
        expectedModCount = modCount;
    } catch (IndexOutOfBoundsException ex) {
        throw new ConcurrentModificationException();
    }
}
public void add(E e) {//添加元素
    checkForComodification();

    try {
        int i = cursor;
        AbstractList.this.add(i, e);
        lastRet = -1;
        cursor = i + 1;
        expectedModCount = modCount;
    } catch (IndexOutOfBoundsException ex) {
        throw new ConcurrentModificationException();
    }
}

6 子列表subList

仅仅只是拿到原来List的子序列的引用

修改subList 起始就是修改原来的List

private final AbstractList<E> l;
private final int offset;
private int size;

SubList(AbstractList<E> list, int fromIndex, int toIndex) {
    if (fromIndex < 0)
        throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
    if (toIndex > list.size())
        throw new IndexOutOfBoundsException("toIndex = " + toIndex);
    if (fromIndex > toIndex)
        throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                           ") > toIndex(" + toIndex + ")");
    l = list;
    offset = fromIndex;
    size = toIndex - fromIndex;
    this.modCount = l.modCount;
}

其他的方法和list差不多 只是需要加上offset偏移量 例如

public E set(int index, E element) {
    rangeCheck(index);
    checkForComodification();
    return l.set(index+offset, element);
}

猜你喜欢

转载自blog.csdn.net/gongsenlin341/article/details/107879311