java list遍历

来源:互联网 发布:台式电脑怎么链接网络 编辑:程序博客网 时间:2024/06/04 05:08
There are primarily 3 ways I can think of to traverse a java.util.List:•Using a traditional for loop;•Using a simplified for loop, or "foreach" statement in JDK 5 ;•Using java.util.Iterator?12345678910111213141516 public static void traverse(List data) {    System.out.println("Using simplified for loop/foreach:");    for(Object obj : data) {        System.out.println(obj);    }     System.out.println("Using for loop:");    for(int i = 0, n = data.size(); i < n; i++) {        System.out.println(data.get(i));    }     System.out.println("Using Iterator:");    for(Iterator it = data.iterator(); it.hasNext();) {        System.out.println(it.next());    }} I always use the for loop and JDK 5 enhanced for loop, and avoid using Iterator to traverse List. If you see other ways, feel free to add them in comment section.


 

原创粉丝点击