java 迭代器与ArrayList中的迭代器

public interface Iterator<E> {
    boolean hasNext();//有元素可以迭代,则返回 true。
    E next();//返回迭代的下一个元素。
    default void remove() {
        //从底层集合中删除此迭代器返回的最后一个元素(可选操作)。 
        throw new UnsupportedOperationException("remove");
    }
    //对每个剩余元素执行给定的操作,直到所有元素都被处理或动作引发异常。
    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}
简单实现
public class IteratorImpl implements Iterator {
    private final Object[] elementData;
    private int nextIndex = 0;// 下一个索引
    int expectedModCount = elementData.length;// 操作数
    public IteratorImpl(Object[] elementData) {
        this.elementData = elementData;
    }

    @Override
    public boolean hasNext() {//:如果仍有元素可以迭代,则返回 true。
        return nextIndex!=elementData.length;
    }

    @Override
    public Object next() {//返回迭代的下一个元素。
 		checkForComodification();
 		
        if (nextIndex>=elementData.length)
            throw new IndexOutOfBoundsException("索引越界");
        nextIndex++;
        return elementData[nextIndex-1];
    }

    public static void main(String[] args) {
        String str0 = "abc";
        String str1 = "123";
        String str3 = "3rs";
        String[] data = {str0,str1,str3};
        IteratorImpl iterator = new IteratorImpl(data);
        for (int i = 0; i < 5; i++) {
            if (iterator.hasNext()){
                System.out.println(iterator.next());
            }
        }
    }
}

ArrayList中的迭代器

// 内部类

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;// 操作数
        Itr() {}
        public boolean hasNext() {
            return cursor != size;
        }
        @SuppressWarnings("unchecked")
        public E next() {
//使用迭代器的过程中,不要随意改变集合长度,否则,会出现ConcurrentModificationException(并发修改异常)
            checkForComodification();
            ///源码///
            //final void checkForComodification() {
            //    if (modCount != expectedModCount)throw new ConcurrentModificationException();
            //}
            /
            //ConcurrentModificationException
            int i = cursor;
            if (i >= size)
                //Exception in thread "main" java.util.NoSuchElementException->没有这样的元素
             /*
                 *原因:我们存元素的个数,和调用next()方法的次数不符合,所以出现了问题
				*解决:不要在while中连续多次next()
			*/
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();
            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
        @Override
        public void forEachRemaining(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i < size) {
                final Object[] es = elementData;
                if (i >= es.length)
                    throw new ConcurrentModificationException();
                for (; i < size && modCount == expectedModCount; i++)
                    action.accept(elementAt(es, i));
                // update once at end to reduce heap write traffic
                cursor = i;
                lastRet = i - 1;
                checkForComodification();
            }
        }
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值