114_容器_迭代器遍历List和Set_List迭代器源代码分析

Iterator接口:

  • 所有实现了Collection接口的容器类都有一个iterator方法用以返回一个实现Iterator接口的对象

  • Iterator对象称作为迭代器,以方便的对容器内元素的遍历操作

  • Iterator接口定义了如下方法:

    1. boolean hashNext(); //判断是否有元素没有被遍历
    2. Object next(); //返回游标当前位置的元素并将游标移动到下一个位置
    3.  void remove(); //删除游标左边的元素,在执行完next之后该操作只能执行一次。
public class Test{
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");

        //通过索引遍历List
        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }
        //通过迭代器遍历List
        for(Iterator iter1 = list.iterator();iter1.hasNext();){
            String str = (String) iter1.next();
            System.out.println(str);
            iter1.remove();
            //iter1.remove();
        }

        System.out.println(list.size()+"******");

        Set set = new HashSet();
        set.add("高1");
        set.add("高2");
        set.add("高3");

        //通过迭代器遍历Set
//      Iterator iter = set.iterator();
//      while(iter.hasNext()){
        for(Iterator iter = set.iterator();iter.hasNext();){
            String str = (String) iter.next();
            System.out.println(str);
        }   
    }
}

list迭代器的源码分析

private class Itr implements Iterator<E> {
        int cursor = 0;

        int lastRet = -1;

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

        public E next() {
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();
            try {
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值