List源码解析

  • Post author:
  • Post category:其他


开始看一下集合Collection,List是Collection的一个子接口,主要是看一下其下的几个类。

1、AbstractList

2、ArrayList

3、Collections.synchronizedList

4、Vector

5、LinkedList

6、CopyOnWriteArrayList


一、AbstractList

这是一个抽象类,其是实现List接口基础类,像ArrayList、LinkedList和Vector都是继承此抽象类的。

1》如果要实现一个不可变的列表,必须实现get(int) 和size()方法

2》如果要实现一个可修改的列表,必须实现set(int,E),如果列表大小可变,必须另外实现add(int,E)和remove(int)方法

其内置了两个迭代器,是Itr和ListItr,继承关系如下

(1)Itr


private class Itr implements Iterator<E> {
    //游标
    int cursor = 0;
    
    //调用next方法时当前的下标索引值
    //,如果调用了remove方法,则重置为-1  
    int lastRet = -1;

    //列表被修改的次数,比如增、删、改、扩容等操作
    int expectedModCount = modCount;
    //是否还有元素
    public boolean hasNext() {
        return cursor != size();
    }
    //返回下一个元素
    public E next() {
        checkForComodification();
        try {
            int i = cursor;
            //get方法是调用具体实现类的
            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);
            if (lastRet < cursor)
                cursor--;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException e) {
            throw new ConcurrentModificationException();
        }
  



版权声明:本文为weixin_37337210原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。