Java基础巩固系列 遍历集合的方法

代码示例:


public class TestIterator {

    //面试题:
    @Test
    public void testFor3() {
        String[] str = new String[]{"AA", "BB", "CC"};

        for (String s : str) {  //原理:将str中的每一个元素赋给String s,s是一个局部变量,s值的修改不会对str本身造成的影响
            s = "MM";
            System.out.println(s);
        }

        for (int i = 0; i < str.length; i++) {
            System.out.println(str[i]);
        }
    }


    @Test
    public void testFor2() {
        String[] str = new String[]{"AA", "BB", "CC"};

        for (int i = 0; i < str.length; i++) {
            str[i] = i + "";
        }

        for (int i = 0; i < str.length; i++) {
            System.out.println(str[i]);
        }
    }

    //***********************************************************************
    //使用增强for循环实现数组的遍历
    @Test
    public void testFor1() {
        String[] str = new String[]{"AA", "BB", "CC"};
        for (String s : str) {
            System.out.println(s);
        }
    }


    //使用增强for循环实现集合的遍历
    @Test
    public void test3() {
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(new String("AA"));
        coll.add(new Date());
        coll.add("BB");
        coll.add(new Person("MM", 23));

        for (Object i : coll) {
            System.out.println(i);
        }
    }

    //错误的写法:使用迭代器Iterator实现集合的遍历
    @Test
    public void test2() {
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(new String("AA"));
        coll.add(new Date());
        coll.add("BB");
        coll.add(new Person("MM", 23));

        Iterator i = coll.iterator();
        while ((i.next()) != null) {
            //java.util.NoSuchElementException
            System.out.println(i.next());
        }
    }

    //正确的写法
    @Test
    public void test1() {
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(new String("AA"));
        coll.add(new Date());
        coll.add("BB");
        coll.add(new Person("MM", 23));

        Iterator i = coll.iterator();
        while (i.hasNext()) {
            System.out.println(i.next());
        }
    }
}

面试题结果:

MM
MM
MM
AA
BB
CC

 

迭代器遍历示意图:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值