Java集合之AbstractList抽象类

本文深入探讨了 Java 中 AbstractList 类的设计与实现细节,解析了其核心方法的运作原理及内部迭代器的实现机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//此类提供 List 接口的骨干实现,以最大限度地减少实现"随机访问"数据存储(如数组)支持的该接口所需的工作。
//对于连续的访问数据(如链表),应优先使用 AbstractSequentialList,而不是此类               jdk1.7    java.util
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
    protected AbstractList() {
    }
    public boolean add(E e) {    //将指定的元素添加到此列表的尾部
        add(size(), e);
        return true;
    }
    abstract public 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();
    }
    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(0, size());
    }
    public boolean addAll(int index, Collection<? extends E> c) {//将指定 collection 中的所有元素都插入到列表中的指定位置
        rangeCheckForAdd(index);//参数有效性检查
        boolean modified = false;
        for (E e : c) {
            add(index++, e);
            modified = true;
        }
        return modified;//成功则返回true
    }
    public Iterator<E> iterator() {//获取该list的迭代器
        return new Itr();
    }
    public ListIterator<E> listIterator() {//获取该list的双向迭代器
        return listIterator(0);
    }
    //返回列表中元素的列表迭代器(按适当顺序),从列表的指定位置开始。指定的索引表示 next的初始调用所返回的第一个元素
    public ListIterator<E> listIterator(final int index) {
        rangeCheckForAdd(index);//参数有效性检查
        return new ListItr(index);
    }
    protected transient int modCount = 0;//实际修改次数 。transient表示不进行序列化
    
    private class Itr implements Iterator<E> {//内部迭代器的实现,继承Iterator接口
        int cursor = 0;//游标,下一个要访问的元素的索引
        int lastRet = -1;//表示上一个访问的元素的索引
        int expectedModCount = modCount;//表示对ArrayList修改次数的期望值,它的初始值为modCount(表示实际修改次数),初始值为0
        public boolean hasNext() {//是否有元素可以迭代
            return cursor != size();//当游标不等于个数时返回true
        }
        public E next() {//next方法
        	//判断expectedModCount是否等于modCount,当调用迭代器时,又使用了集合里的add或者remove方法就报错,应使用迭代器里的remove方法
            checkForComodification();
            try {
                int i = cursor;
                E next = get(i);//获取当前值
                lastRet = i;//更新lastRet
                cursor = i + 1;//保存下一次要迭代的元素的索引
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }
        public void remove() {//移除
            if (lastRet < 0)
                throw new IllegalStateException();
            //判断expectedModCount(期望修改次数)是否等于modCount(实际修改次数),不等则抛出异常
            checkForComodification();//
            try {
            	//调用外部类的remove方法,会对modCount加1,并且lastRet初始值为-1,必须调用next方法后才能调用该remove方法
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;//让cursor减1,保证删除元素后的下一次迭代是正确的元素
                lastRet = -1;//给lastRet重新赋值
                expectedModCount = modCount;//上面加1了,所以此处需要重新赋值
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }
        final void checkForComodification() {//校验expectedModCount(期望修改次数)是否等于modCount(实际修改次数)
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
    //实现双向迭代器接口
    private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            cursor = index;//构造器,开始迭代的地方
        }
        public boolean hasPrevious() {
            return cursor != 0;//索引为0时,就没有前一个元素了
        }
        public E previous() {//反向迭代
            checkForComodification();//校验expectedModCount(期望修改次数)是否等于modCount(实际修改次数),原理同前面
            try {
                int i = cursor - 1;//索引-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)//设置点的索引小于0抛出异常
                throw new IllegalStateException();//
            checkForComodification();//校验expectedModCount(期望修改次数)是否等于modCount(实际修改次数),原理同前面
            try {
                AbstractList.this.set(lastRet, e);//调用外部类的set进行修改,会让modCount加1,所以需要重新赋值
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
        public void add(E e) {//在迭代的位置增加
            checkForComodification();//校验expectedModCount(期望修改次数)是否等于modCount(实际修改次数),原理同前面
            try {
                int i = cursor;
                AbstractList.this.add(i, e);//调用外部类的add进行修改,会让modCount加1,所以需要重新赋值
                lastRet = -1;//每次增加之后lastRet赋值为-1,所以不能即刻进行删除,需重新调用next方法
                cursor = i + 1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }
    public boolean equals(Object o) {
        if (o == this)//引用相等则必然相等
            return true;
        if (!(o instanceof List))//是否是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());//如果元素个数不等则不相等
    }
    public int hashCode() {//hashCode计算
        int hashCode = 1;
        for (E e : this)
            hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
        return hashCode;
    }
    protected void removeRange(int fromIndex, int toIndex) {//移除集合中从fromIndex(包括)到toIndex(不包括)直接的元素
        ListIterator<E> it = listIterator(fromIndex);//从当前位置开始迭代
        for (int i=0, n=toIndex-fromIndex; i<n; i++) {
            it.next();
            it.remove();
        }
    }
    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();
    }
}
//获取集合中从fromIndex(包括)到toIndex(不包括)元素组成新的集合,是浅复制,引用会互相影响
public List<E> subList(int fromIndex, int toIndex) {
	//RandomAccess接口是List实现所使用的标记接口,用来表明其支持快速(通常是固定时间)随机访问
	//在对List特别的遍历算法中,要尽量来判断是属于RandomAccess(如ArrayList)还是SequenceAccess(如LinkedList)
	//因为适合RandomAccess List的遍历算法,用在SequenceAccess List上就差别很大
    return (this instanceof RandomAccess ?   //只有ArrayList实现了RandomAccess接口,判断是否是ArrayList或其子类
            new RandomAccessSubList<>(this, fromIndex, toIndex) :
            new SubList<>(this, fromIndex, toIndex));
}
class SubList<E> extends AbstractList<E> {
    private final AbstractList<E> l;//l仅仅是直接复制了原list的引用,所以对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;//复制原list引用
        offset = fromIndex;//偏移量
        size = toIndex - fromIndex;//大小
        //this.modCount访问自身的modCount;l.modCount访问外部类的modCount(l是指向外部类的一个引用,直接复制引用过来的)
        this.modCount = l.modCount;
    }

    public E set(int index, E element) {//修改元素
        rangeCheck(index);//参数校验
        //判断this.modCount是否等于l.modCount,如果用SubList的同时对外部类集合进行修改(会影响到modCount的方法),抛出异常
        checkForComodification();
        return l.set(index+offset, element);
    }

    public E get(int index) {//获取元素
        rangeCheck(index);//参数校验
      //判断this.modCount是否等于l.modCount,如果用SubList的同时对外部类集合进行修改(会影响到modCount的方法),抛出异常
        checkForComodification();
        return l.get(index+offset);
    }

    public int size() {//大小
    	//判断this.modCount是否等于l.modCount,如果用SubList的同时对外部类集合进行修改(会影响到modCount的方法),抛出异常
        checkForComodification();
        return size;
    }

    public void add(int index, E element) {//新增元素
        rangeCheckForAdd(index);
      //判断this.modCount是否等于l.modCount,如果用SubList的同时对外部类集合进行修改(会影响到modCount的方法),抛出异常
        checkForComodification();
        l.add(index+offset, element);
        this.modCount = l.modCount;
        size++;
    }

    public E remove(int index) {//移除元素
        rangeCheck(index);
      //判断this.modCount是否等于l.modCount,如果用SubList的同时对外部类集合进行修改(会影响到modCount的方法),抛出异常
        checkForComodification();
        E result = l.remove(index+offset);
        this.modCount = l.modCount;
        size--;
        return result;
    }

    protected void removeRange(int fromIndex, int toIndex) {//移除fromIndex(包括)到toIndex(不包括)的范围内元素
    	//判断this.modCount是否等于l.modCount,如果用SubList的同时对外部类集合进行修改(会影响到modCount的方法),抛出异常
        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) {//从index处开始增加集合内的元素
        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) {//构建新的list,浅复制
        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;
    }
  //判断this.modCount是否等于l.modCount,如果用SubList的同时对外部类集合进行修改(会影响到modCount的方法),抛出异常
    private void checkForComodification() {
        if (this.modCount != l.modCount)
            throw new ConcurrentModificationException();
    }
}
//实现了RandomAccess接口,标记接口(Marker),它没有任何方法。如果List子类实现了RandomAccess接口,那就表示它能够快速随机访问存储的元素。
class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
    RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
        super(list, fromIndex, toIndex);
    }

    public List<E> subList(int fromIndex, int toIndex) {//构建新的list
        return new RandomAccessSubList<>(this, fromIndex, toIndex);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值