集合框架中取出元素的方式for循环增强型与一般形式for循环的对比

来源:互联网 发布:mui框架 js 构建dom 编辑:程序博客网 时间:2024/06/06 16:55

以前我们在遍历元素时,一般情况下是采用以下格式:

        Collection coll = new ArrayList();        coll.add("a1");        coll.add("a2");        coll.add("a3");        coll.add("a4");        for (Iterator it = coll.iterator(); it.hasNext();) {            Object obj = it.next();            System.out.println(obj);        }

在JDK1.5以后,Comparable接口继承了Iterable接口。
增强for循环:用于遍历Collection集合或者数组

格式:

for(元素类型 变量:collection容器or数组){    System.out.println(变量);}

例如:

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

传统的for循环与增强型for循环的区别:
传统for循环可以在任何情况下使用,而增强型的for循环要求有被遍历的目标,目标只能是Collection或者数组(建议数组使用传统方式)。

0 0
原创粉丝点击