package Test;
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorTime {
public static void main(String[] args){
final int LENGTH = 10;
ArrayList list = new ArrayList();
for(int i = 0; i < LENGTH; i++){
list.add(i, new Integer(i));
}
System.out.println("the size of ArrayList is " + LENGTH);
long start = System.currentTimeMillis();
int length = list.size();
for(int i = 0; i < length; i++){
//System.out.print(list.get(i).toString()+"\t");
}
long end = System.currentTimeMillis();
System.out.println("内部遍历用时:" + (end-start) + "ms");
//System.out.println("");
start = System.currentTimeMillis();
Iterator it = list.iterator();
while(it.hasNext()){
it.next();
//System.out.print(it.next().toString()+"\t");
}
end = System.currentTimeMillis();
System.out.println("Iterator遍历用时:" + (end-start) + "ms");
}
}
the size of ArrayList is 10:
内部遍历用时:0ms
Iterator遍历用时:0ms
the size of ArrayList is 100:
内部遍历用时:0ms
Iterator遍历用时:0ms
the size of ArrayList is 10000:
内部遍历用时:0ms
Iterator遍历用时:10ms
the size of ArrayList is 100000:
内部遍历用时:0ms
Iterator遍历用时:20ms
the size of ArrayList is 1000000:
内部遍历用时:0ms
Iterator遍历用时:120ms
你大约可以看出差距