JDK源码解读第十章:java.util.AbstractList

161 阅读5分钟

AbstractList

1.AbstractList声明

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {}

这是一个抽象类,除了实现List接口,AbstractList还继承了AbstractCollection抽象类。重点关注一下经常使用的增删改查方法的实现。

2.add(E e)

 	public boolean add(E e) {
        add(size(), e);
        return true;
    }
    
    public void add(int index, E element) {
        throw new UnsupportedOperationException();
    }

添加指定元素到列表末端。此方法抛出IndexOutOfBoundsException异常。所以如果需要修改可变list需要重写此方法,不可变list抛出异常。

3.get(int index)

 	abstract public E get(int index);

抽象方法。必须重写才能使用。

4.get(int index)

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

更新和删除方法,同add,需要修改可变list的时候需要重写,不然会抛出异常。

5.indexOf(Object o)

 	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;
    }
    
    public ListIterator<E> listIterator() {
        return listIterator(0);
    }
    
    public ListIterator<E> listIterator(final int index) {
        rangeCheckForAdd(index);

        return new ListItr(index);
    }
    
    private void rangeCheckForAdd(int index) {
        if (index < 0 || index > size())
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size();
    }

查找指定元素在列表中第一次出现的索引。通过列表迭代器的迭代实现。

7.lastIndexOf(Object o)

 	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 ListIterator<E> listIterator() {
        return listIterator(0);
    }
    
    public ListIterator<E> listIterator(final int index) {
        rangeCheckForAdd(index);

        return new ListItr(index);
    }
    
    private void rangeCheckForAdd(int index) {
        if (index < 0 || index > size())
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size();
    }

查找指定元素在列表中最后一次出现的索引。通过列表迭代器的迭代实现。

8.clear()

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

清空列表,使用迭代器循环,然后remove()。

9.iterator()

	public Iterator<E> iterator() {
    	return new Itr();
	}
    
    private class Itr implements Iterator<E> {
        //下一次调用next()方法返回元素的索引
        int cursor = 0;

        //最近一次调用next()方法返回元素的索引;如果发生一次remove()操作,则被重置为-1
        int lastRet = -1;

        //AbstractList定义的modCount成员变量如下,它主要记录列表实例创建之后,发生结构性修改的次数。用于判断列表是否在创建完迭代器之后,发生并发修改的异常。
        int expectedModCount = modCount;

		//判断迭代器中是否还有元素,如果cursor等于列表size,则表示没有
        public boolean hasNext() {
            return cursor != size();
        }

		//返回下一个元素
        public E next() 
        	//先检查在迭代器创建完之后是否发生过结构性修改,是则抛出异常;否则继续执行
            checkForComodification();
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

		//依赖列表的remove()方法,如果列表没有实现该方法,那么调用迭代器的这个方法将抛出UnsupportedOperationException
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                //调用一次此方法,就将lastRet重置为-1
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }
		
        //判断在迭代器生成之后,列表是否发生(不是通过迭代器做到的)结构性修改
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
    
    //返回一个在列表元素之上的列表迭代器。
    public ListIterator<E> listIterator() {
        return listIterator(0);
    }
    
    public ListIterator<E> listIterator(final int index) {
        rangeCheckForAdd(index);

        return new ListItr(index);
    }
    
    //检查数组是否越界
    private void rangeCheckForAdd(int index) {
        if (index < 0 || index > size())
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

	//抛出数据越界异常
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size();
    }
    
        private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            cursor = index;
        }

		//判断列表迭代器中前面是否还有元素
        public boolean hasPrevious() {
            return cursor != 0;
        }

		//返回列表迭代器中前面一个元素(即,当前位置cursor减1的位置处的元素)
        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;
        }

		//更新最近一次返回的元素(即,lastRet索引指向的元素)
        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();
            }
        }

		//添加指定元素到列表迭代器的当前位置处,同样也是利用列表的add(E)方法实现
        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();
            }
        }
    }

迭代器相关的处理,大概了解了下,如果有兴趣的读者可以自己详细去了解。

10.subList(int fromIndex, int toIndex)

	public List<E> subList(int fromIndex, int toIndex) {
        return (this instanceof RandomAccess ?
                new RandomAccessSubList<>(this, fromIndex, toIndex) :
                new SubList<>(this, fromIndex, toIndex));
    }
    
    //RandomAccessSubList类继承自SubList,并实现了RandomAccess接口
    class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
    	RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
        	//通过调用父类SubList的构造方法创建一个子列表实例
        	super(list, fromIndex, toIndex);
    		}

		////返回一个子列表
    	public List<E> subList(int fromIndex, int toIndex) {
        	return new RandomAccessSubList<>(this, fromIndex, toIndex);
    		}
	}
    
    //SubList类继承自AbstractList抽象类,因此它的实例列表可以使用AbstractList的各种已经实现的方法。  
    class SubList<E> extends AbstractList<E> {
    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;
        //modCount也与原列表相同(这是因为它与原列表共享数据,彼此发生的结构性修改会反映到对方)
        this.modCount = l.modCount; 
    }
 
    public E set(int index, E element) {
        rangeCheck(index);
        checkForComodification();
        return l.set(index+offset, element);
    }
 
    public E get(int index) {
    	//判断索引是否超出范围
        rangeCheck(index);  
        //判断是否发生过并发结构性修改(通过原列表或其的迭代器发生的remove()操作,而不是此子列表)
        checkForComodification();
        return l.get(index+offset);
    }
 
    public int size() {
        checkForComodification();
        return size;
    }
 
    public void add(int index, E element) {
    	//判断索引是否超出范围
        rangeCheckForAdd(index);     
        checkForComodification();
        l.add(index+offset, element);
        //保持modCount与原列表相同(上面调用了原列表的add()方法,原列表的modCount加了1)
        this.modCount = l.modCount;   
        size++;
    }
 
    public E remove(int index) {
        rangeCheck(index);
        checkForComodification();
        E result = l.remove(index+offset);
        this.modCount = l.modCount;
        //这里更新的是子列表的size,原列表的size在上面l.remove()方法的执行过程中就已经更新完毕
        size--;  
        return result;
    }
 
    protected void removeRange(int fromIndex, int toIndex) {
        checkForComodification();
        l.removeRange(fromIndex+offset, toIndex+offset);
        this.modCount = l.modCount;
        size -= (toIndex-fromIndex);
    }
 
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }
 
    public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);
        int cSize = c.size();
        if (cSize==0)
            return false;
 
        checkForComodification();
        l.addAll(offset+index, c);
        this.modCount = l.modCount;
        size += cSize;
        return true;
    }
 
    public Iterator<E> iterator() {
        return listIterator();
    }
 
    public ListIterator<E> listIterator(final int index) {
        checkForComodification();
        rangeCheckForAdd(index);
 
        return new ListIterator<E>() {
            private final ListIterator<E> i = l.listIterator(index+offset);
 
            public boolean hasNext() {
                return nextIndex() < size;
            }
 
            public E next() {
                if (hasNext())
                    return i.next();
                else
                    throw new NoSuchElementException();
            }
 
            public boolean hasPrevious() {
                return previousIndex() >= 0;
            }
 
            public E previous() {
                if (hasPrevious())
                    return i.previous();
                else
                    throw new NoSuchElementException();
            }
 
            public int nextIndex() {
                return i.nextIndex() - offset;
            }
 
            public int previousIndex() {
                return i.previousIndex() - offset;
            }
 
            public void remove() {
                i.remove();
                SubList.this.modCount = l.modCount;
                size--;
            }
 
            public void set(E e) {
                i.set(e);
            }
 
            public void add(E e) {
                i.add(e);
                SubList.this.modCount = l.modCount;
                size++;
            }
        };
    }
   //返回这个子列表的子列表
    public List<E> subList(int fromIndex, int toIndex) {
        return new SubList<>(this, fromIndex, toIndex);
    }
 
    private void rangeCheck(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
 
    private void rangeCheckForAdd(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
 
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }
 
    private void checkForComodification() {
        if (this.modCount != l.modCount)
            throw new ConcurrentModificationException();
    }
}

此方法返回一个类型为AbstractList子类的列表。返回的列表基于原列表,如果原列表实现了RandomAccess接口,那么则返回一个既继承AbstractList抽象类又实现RandomAccess接口的子类的实例;否则,返回一个只继承AbstractList抽象类的实例。