import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* IteratorTest
* @author SageZk
*/
public class IteratorTest {
public static long testForloops(List<String> list) {
long start = 0L, end = 0L;
@SuppressWarnings("unused")
String le = null;
start = System.nanoTime();
for (int i = list.size() - 1; i >= 0; --i) {
le = list.get(i);
}
end = System.nanoTime();
return end - start;
}
public static long testIterator(List<String> list) {
long start = 0L, end = 0L;
@SuppressWarnings("unused")
String le = null;
start = System.nanoTime();
Iterator<String> it = list.iterator();
while (it.hasNext()) {
le = it.next();
}
end = System.nanoTime();
return end - start;
}
public static void main(String[] args) {
//测试列表长度
final int LEN = 10000;
//初始化测试用数据
List<String> arraylist = new ArrayList<String>();
List<String> linkedlist = new LinkedList<String>();
for (int i = 0; i < LEN; ++i) {
String s = Integer.toString(i, 2);
arraylist.add(s);
linkedlist.add(s);
}
//打印测试结果
final String FORMAT = "%1$-16s%2$-16s%3$16d\n";
System.out.println("List\t\tType\t\tTime(nanoseconds)");
System.out.println("-------------------------------------------------");
System.out.printf(FORMAT, "ArrayList", "for", testForloops(arraylist));
System.out.printf(FORMAT, "ArrayList", "Iterator", testIterator(arraylist));
System.out.printf(FORMAT, "LinkedList", "for", testForloops(linkedlist));
System.out.printf(FORMAT, "LinkedList", "Iterator", testIterator(linkedlist));
}
}
以下是 3 组测试结果:
[code=BatchFile]List Type Time(nanoseconds)
-------------------------------------------------
ArrayList for 1189258
ArrayList Iterator 2365594
LinkedList for 152396254
LinkedList Iterator 2340801
List Type Time(nanoseconds)
-------------------------------------------------
ArrayList for 1235701
ArrayList Iterator 4249982
LinkedList for 149825606
LinkedList Iterator 2525531
List Type Time(nanoseconds)
-------------------------------------------------
ArrayList for 1198267
ArrayList Iterator 2584617
LinkedList for 150382451
LinkedList Iterator 2347994
[/code]
帽子大哥的总结:
使用 Iterator 的好处在于可以使用相同方式去遍历集合(List 是有序集合)中元素,而不用考虑集合类的内部实现(只要它实现了 java.lang.Iterable 接口)。
比如楼主例子中,如果使用 Iterator 来遍历集合中元素,一旦不再使用 List 转而使用 TreeSet 来组织数据,那遍历元素的代码不用做任何修改,如果使用 for 来遍历,那所有遍历此集合的算法都得做相应调整。
这是在一篇问答帖子上看到的,当时觉得帽子大哥说得比较经典,故copy下来存档了。