集合迭代器增删改异常

**
 * @Author LWL
 * @Date 2022/5/21 23:49
 * @TODO 集合异常问题
 */
public class Test {

    //迭代器内部
    /*public Iterator<E> iterator() {
        return new ArrayList.Itr();
    }*/

    /**
     * expectedModCount为预期修改集合次数,modCount 为实际修改集合次数。
     * Itr类中初始状态时expectedModCount和modCount 相等,在调用其中next方法时会对两者进行判断。
     * 但是ArrayList中的add方法中每次添加一个元素,modCount 会自动加一。故导致在next方法中判断两者不相等,故出现并发修改异常。
     */

    /*private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }*/


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


    //add 方法调用
    /*private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }*/
    public static void main(String[] args) {
        ArrayList<Object> list = new ArrayList<>();
        //改成ListIterator迭代器(iterator的子接口),ListIterator可以直接往集合中添加元素,
        // 因为ListItr类中有add方法,而且在方法体中会将实际修改集合的次数赋值给预期修改值。
        ListIterator<Object> objectListIterator = list.listIterator();
        while (objectListIterator.hasNext()) {
            objectListIterator.add("");
            objectListIterator.remove();
            objectListIterator.set("");
        }
        //iterator中只有remove()操作
        Iterator<Object> iterator = list.iterator();
        while (iterator.hasNext()) {
            iterator.remove();
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值