for循环、增强for循环和迭代器的区别

1、迭代器是用于方便集合遍历的,实现了Iterable接口的集合都可以使用迭代器来遍历。使用迭代器遍历元素时,除了查看之外,只能做remove操作。

2、增强for循环,内部使用的是迭代器,所以它的操作对象是数组和可以使用迭代器的集合。遍历时只能查看,无法修改、删除、增加。

所以如果需要对遍历的对象做增删修改的操作,使用普通的for循环来操作。

迭代器/增强for循环

    @Test
    public void test003(){
        List<Integer> list = new ArrayList<>();
        list.add(22);
        list.add(242);
        list.add(232);
        list.add(212);
        iteratorApply(list);
        forApple(list);

    }

    //迭代器
    public void iteratorApply(List<Integer> list){
        Iterator<Integer> it = list.iterator();
        while (it.hasNext()){
            int num = it.next();
            System.out.println(num);
            if (num == 22){
                it.remove();
            }
        }
        System.out.println(list.size());
    }

    //增强for循环
    public void forApple(List<Integer> list){
        for (int num : list){
            System.out.println(num);
        }
    }

猜你喜欢

转载自www.cnblogs.com/whalesea/p/13168216.html