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

迭代器遍历示意图:

 

猜你喜欢

转载自blog.csdn.net/Peter__Li/article/details/88972636
今日推荐