java 集合框架-AbstractList

Posted 智公博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 集合框架-AbstractList相关的知识,希望对你有一定的参考价值。

AbstractList 作为具体List型具体类,实现AbstractCollection抽象类、继承List接口,实现了部分方法
- indexOf
- lastIndexOf
- subList
- addAll
- iterator
- listIterator
- equals
- hashCode

下面源码分析一些较复杂的方法实现

一、实现List的接口方法

indexOf、lastIndexOf、subList

    public int indexOf(Object o) 
        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;
    

indexOf 方法使用List特有的ListIterator实现,在遍历判断中,使用List双向的特性,返回index,不需要每次记录index;
有关listIterator的详情,后面分析

    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;
    

lastIndexOf 就将ListIterator 双向遍历的特性用的更加完成,直接反向遍历查询;

二、迭代器实现

    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);
    

前面两篇的描述中,都强调迭代器的重要性,在AbstractList就可以看到它的实现了:

    private class Itr implements Iterator<E> 
        /**
         * Index of element to be returned by subsequent call to next.
         */
        int cursor = 0; //游标,表示当前迭代处于的位置;初始为0,总是从第一个元素开始

        /**
         * Index of element returned by most recent call to next or
         * previous.  Reset to -1 if this element is deleted by a call
         * to remove.
         */
        int lastRet = -1; //表示当前迭代处于位置的前一个下标,remove移除元素就是这个下标对应的元素,移除后恢复为-1,表示remove只能在每次next方法后调用一次

        /**
         * The modCount value that the iterator believes that the backing
         * List should have.  If this expectation is violated, the iterator
         * has detected concurrent modification.
         */
        int expectedModCount = modCount;//这个整型数用来保证迭代时,集合没有发生并发的修改

        public boolean hasNext() 
            return cursor != size();
        

        public E next() 
            checkForComodification();
            try 
                int i = cursor;
                E next = get(i);
                lastRet = i; //记录位置
                cursor = i + 1; //每次next,游标后移一位
                return next;
             catch (IndexOutOfBoundsException e) 
                checkForComodification();
                throw new NoSuchElementException();
            
        

        public void remove() 
            if (lastRet < 0) //不可在next方法前、或一次next方法后两次调用
                throw new IllegalStateException();
            checkForComodification();

            try 
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                lastRet = -1;
                expectedModCount = modCount;
             catch (IndexOutOfBoundsException e) 
                throw new ConcurrentModificationException();
            
        

        final void checkForComodification()  //该方法检测是否发生了并发修改
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        
    

迭代器的实现并不复杂,唯有并发修改的快速失败(ConcurrentModificationException),只从上面的源码还看不出来,需要知道modCount值的变化,从迭代器的remove方法可以猜测到,在对集合修改时,这个值是会发送变化,当处于迭代时,其他线程修改集合导致这个值改变,那么可以检测到并发修改;

我们来看下这个属性在AbstractList中的定义:

    /**
     * The number of times this list has been <i>structurally modified</i>.
     * Structural modifications are those that change the size of the
     * list, or otherwise perturb it in such a fashion that iterations in
     * progress may yield incorrect results.
     *
     * <p>This field is used by the iterator and list iterator implementation
     * returned by the @code iterator and @code listIterator methods.
     * If the value of this field changes unexpectedly, the iterator (or list
     * iterator) will throw a @code ConcurrentModificationException in
     * response to the @code next, @code remove, @code previous,
     * @code set or @code add operations.  This provides
     * <i>fail-fast</i> behavior, rather than non-deterministic behavior in
     * the face of concurrent modification during iteration.
     *
     * <p><b>Use of this field by subclasses is optional.</b> If a subclass
     * wishes to provide fail-fast iterators (and list iterators), then it
     * merely has to increment this field in its @code add(int, E) and
     * @code remove(int) methods (and any other methods that it overrides
     * that result in structural modifications to the list).  A single call to
     * @code add(int, E) or @code remove(int) must add no more than
     * one to this field, or the iterators (and list iterators) will throw
     * bogus @code ConcurrentModificationExceptions.  If an implementation
     * does not wish to provide fail-fast iterators, this field may be
     * ignored.
     */
    protected transient int modCount = 0;

注释大概说明三个点,和我们猜测的一致:
- 记录在结构上修改集合的次数
- 这个字段被用于迭代器,用于提供并发修改的快速失败机制
- 子类可以选择是否使用这个机制,实现只需要在修改结构的方法递增这个值即可;不实现直接忽略该值

接下来再看下ListIterator:

    private class ListItr extends Itr implements ListIterator<E> 
        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;
             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();
            
        
    

可以看出,实现和Itr很相似,增加几个特性:
- 允许指定下标开始迭代
- 支持双向迭代
- 允许修改当前下标元素
- 允许在当前下标添加元素

Object 声明的三个常需实现方法:toString、equals、hashCode;AbstractCollection已经实现了toString,
AbstractList实现了剩下的两个方法:

    public int hashCode() 
        int hashCode = 1;
        for (E e : this)
            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
        return hashCode;
    

    public boolean equals(Object o) 
        if (o == this)
            return true;
        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();
            if (!(o1==null ? o2==null : o1.equals(o2)))
                return false;
        
        return !(e1.hasNext() || e2.hasNext());
    

两个list相等的条件是类型一样、size一样、每个元素对应相等;

以上是关于java 集合框架-AbstractList的主要内容,如果未能解决你的问题,请参考以下文章

Java集合框架源码——Vector

java集合框架

Java集合框架

Java 集合学习笔记:AbstractList

Java 集合学习笔记:AbstractList

Java 集合深入理解 :AbstractList类