遍历集合和数组的方式

public class Test1 {
    //使用while和iterator的hasNext()与next()方式实现集合的遍历
    @Test
    public void test1(){
        Collection collection = new ArrayList();
        collection.add(123);
        collection.add("AA");
        collection.add(new SimpleDateFormat("HH:mm:ss:SSS").format(new Date()));
        Iterator it = collection.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
    }
    //使用增强FOR循环遍历集合
    @Test
    public void test2(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add("AA");
        coll.add(new SimpleDateFormat("HH:mm:ss:SSS").format(new Date()));

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


    @Test
    public void test3(){
        String[] str = new String[]{"AA","bb","cc","dd"};
        //使用增强FOR循环遍历数组
        for (String s :str){
            System.out.println(s);
        }
        System.out.println("#############");
        //一般for循环遍历数组
        for(int i =0;i<str.length;i++){
            System.out.print(str[i]);
        }
    }

}

猜你喜欢

转载自blog.csdn.net/qq_16246279/article/details/85060512