【Java集合】Iterator迭代器remove()的使用以及使用foreach循环遍历集合元素

Iterator接口remove()方法

注意:

1、 Iterator可以删除集合的元素,但是是遍历过程中通过迭代器对象的remove方 法,不是集合对象的remove方法。

2、如果还未调用next()或在上一次调用 next 方法之后已经调用了 remove 方法,再调用remove都会报IllegalStateException。

 举例:

    //测试Iterator中的remove()
    @Test
    public void test2(){

        Collection coll = new ArrayList();
        coll.add(456);
        coll.add(123);
        coll.add(new Person("Jerry", 20));
        coll.add(new String("Tom"));
        coll.add(false);

        //删除集合中“Tom”
        Iterator iterator = coll.iterator();
        while (iterator.hasNext()){
            Object obj = iterator.next();
            if ("Tom".equals(obj)){
                iterator.remove();
            }
        }
        //遍历
        Iterator iterator1 = coll.iterator();
        while (iterator1.hasNext()){
            System.out.println(iterator1.next());
        }
    }

运行结果如下:

 使用 foreach 循环遍历集合元素

1、Java 5.0 提供了 foreach 循环迭代访问 Collection和数组。

2、遍历操作不需获取Collection或数组的长度,无需使用索引访问元素。

3、 遍历集合的底层调用Iterator完成操作。

4、 foreach还可以用来遍历数组。

 

举例:

    @Test
    public void test1(){
        Collection coll = new ArrayList();
        coll.add(456);
        coll.add(123);
        coll.add(new Person("Jerry", 20));
        coll.add(new String("Tom"));
        coll.add(false);

        //for(集合元素的类型 局部变量 : 集合对象)
        for (Object obj : coll){
            System.out.println(obj);
        }
    }

运行结果如下:

如上方法其实内部仍然调用了迭代器

 我们再看一个例子:

    @Test
    public void test2(){
        int[] arr = new int[]{1,2,3,4,5,6,7};
        //for(数组元素的类型 局部变量 : 数组对象)
        for (int i : arr){
            System.out.print(i + "\t");
        }
    }

运行结果如下:

感谢观看!!! 

猜你喜欢

转载自blog.csdn.net/qq_64976935/article/details/129773812