JDK1.5之后,遍历列表操作至少有三种方法:ForEach操作,迭代器和for循环。
使用方法如下:
String[] strs = new String[]{"1", "2", "3"};
List<String> list = Arrays.asList(strs);
for (String s: list) {//ForEach操作
System.out.println(s);
}
for (Iterator it = list.iterator(); it.hasNext();) {//迭代器
System.out.println(it.next());
}
for (int i=0; i<list.size(); i++) {//for循环
System.out.println(list.get(i));
}
这三种遍历操作效率对比如下:
对于ArrayList:
for循环 > 迭代器 > ForEach操作
对于LinkedList:
迭代器 > ForEach操作,不要使用for循环!
ForEach操作效率小于迭代器的原因是,ForEach循环会被解析成下面的代码:
for (Iterator it = list.iterator(); it.hasNext();) {
String s = (String) it.next();
String s1 = s;//多余的赋值
}
而迭代器遍历被解析为:
String s2;
for (Iterator it = list.iterator(); it.hasNext();) {
s2 = (String) it.next();
}
ForEach循环中存在一步多余的赋值操作。