JAVA集合框架4---AbstractList源码解析

AbstractList类和List接口之间的关系与AbstractCollection类和Collection接口之间的关系一样,AbstractList提供了List接口的默认实现方式,这样如果我们需要实现List接口直接继承AbstractList类即可,而不需要实现List接口中的所有方法,加快开发。

AbstractList的源码如下:

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
    protected AbstractList() {
    }
    //在集合的末尾添加元素
    public boolean add(E e) {
        add(size(), e);
        return true;
    }

    public abstract E get(int index);
    //默认抛出异常
    public E set(int index, E element) {
        throw new UnsupportedOperationException();
    }
    //默认抛出异常
    public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }
    //默认抛出异常
    public E remove(int index) {
        throw new UnsupportedOperationException();
    }
    //查找对象o的索引,找不到返回-1
    public int indexOf(Object o) {
        ListIterator<E> it = listIterator();
        if (o==null) {
            while (it.hasNext())
                if (it.next()==null)
                    return it.previousIndex(); //为什么是返回前一个索引值?因为next()不仅返回下一个元素,还会更新当前位置使其指向下一个元素,所以这里需要返回前一个元素的索引值。
        } else {
            while (it.hasNext())
                if (o.equals(it.next()))
                    return it.previousIndex();
        }
        return -1;
    }
    //从后往前查找对象o的索引,找不到返回-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 {
            while (it.hasPrevious())
                if (o.equals(it.previous()))
                    return it.nextIndex();
        }
        return -1;
    }
    //清空集合中的所有元素
    public void clear() {
        removeRange(0, size());
    }
    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();
        }
    }
    //从指定索引位置开始增加集合c中的所有元素
    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;
    }
    //返回迭代器对象 Itr是成员内部类
    public Iterator<E> iterator() {
        return new Itr();
    }
    //返回List迭代器对象  
    public ListIterator<E> listIterator() {
        return listIterator(0);
    }
    //从指定位置返回List迭代器对象  ListItr是成员内部类
    public ListIterator<E> listIterator(final int index) {
        rangeCheckForAdd(index);

        return new ListItr(index);
    }
}

AbstractList中的Iterator迭代器的实现

    //记录List集合的修改次数,一般扩容,增加元素,删除元素都会增加modCount,修改和查询不会改变modCount
    protected transient int modCount = 0;    
    private class Itr implements Iterator<E> {
        // 下一次next()要返回元素的索引值
        int cursor = 0;

        // 上一次next()返回元素的索引值,即 lastRet = cursor - 1(如果lastRet不为负数的话)
        int lastRet = -1;

        // 记录遍历之前集合的修改次数
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size();
        }
        //next()函数不仅返回下一个元素,还会更新cursor的值,使其指向下一个元素。
        public E next() {
            checkForComodification(); //检测集合结构是否发生变化,如果是就抛出异常
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1; //更新cursor的值
                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;  //更新lastRet的值,所以不能连着两次调用 remove函数
                expectedModCount = modCount; //更新了expectedModCount的值,所以使用迭代器的remove方法可以在遍历的过程中修改集合
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

AbstractList中的ListIterator迭代器的实现

	private class ListItr extends Itr implements ListIterator<E> {
        // 有参构造函数,直接使cursor指向index
		ListItr(int index) {
			cursor = index;
		}

		public boolean hasPrevious() {
			return cursor != 0;
		}

		public E previous() {
			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);
				expectedModCount = modCount; // 更新expectedModCount
			} 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();
			}
		}
	}

猜你喜欢

转载自blog.csdn.net/qq_22158743/article/details/87711808
今日推荐