62,631
社区成员
发帖
与我相关
我的任务
分享
package myTest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedMap;
import java.util.Vector;
public class Test {
public static void main(String[] args)
{
List<Integer> list = new ArrayList<Integer>();
for(int i=0;i<5000000 ;i++){
list.add(11);
}
int size= list.size();
int c1=1;
long start = System.currentTimeMillis();
for(int i=0;i<size;i++){
c1 = list.get(i);
}
long end = System.currentTimeMillis()-start;
System.out.println("for + get(i)方法: " + end);
start = System.currentTimeMillis();
for(int c2:list){
}
end = System.currentTimeMillis()-start;
System.out.println("Iterator(foreach)方法:" + end);
int i = 0;
size = list.size();
start = System.currentTimeMillis();
while(i<size){
c1 = list.get(i);
i++;
}
end = System.currentTimeMillis()-start;
System.out.println("While + get(i)方法:" + end);
start = System.currentTimeMillis();
for(Iterator iterator = list.iterator(); iterator.hasNext();) {
c1 = (Integer) iterator.next();
}
end = System.currentTimeMillis()-start;
System.out.println("for iterator方法:" + end);
}
}
import java.util.*;
public class CMPfor
{
final long N = 1000000;
private ArrayList<Integer> aT = new ArrayList<Integer>();
private LinkedList<Integer> LT = new LinkedList<Integer>();
public CMPfor(){
for(int i = 0; i < N; i++){
aT.add(i);
}
for(int i = 0; i < N; i++){
LT.add(i);
}
}
public void forTest(List<Integer> t){
for(int i = 0; i < t.size();i++){
t.get(i);
}
}
public void foreachTest(List<Integer> t){
for(int j : t){
}
}
public void iteratorTest(List<Integer> t){
Iterator it = t.iterator();
while(it.hasNext()){
it.next();
}
}
public void whileTest(List<Integer> t){
int i = 0;
while(i < N){
t.get(i);
i++;
}
}
public static void main(String[] args){
CMPfor cf = new CMPfor();
long a,b;
System.out.println("ArrayList Test:");
a=System.currentTimeMillis();
cf.forTest(cf.aT);
b=System.currentTimeMillis();
System.out.println("forTest: "+(b-a)+"ms");
a=System.currentTimeMillis();
cf.foreachTest(cf.aT);
b=System.currentTimeMillis();
System.out.println("foreachTest: "+(b-a)+"ms");
a=System.currentTimeMillis();
cf.iteratorTest(cf.aT);
b=System.currentTimeMillis();
System.out.println("iteratorTest: "+(b-a)+"ms");
a=System.currentTimeMillis();
cf.whileTest(cf.aT);
b=System.currentTimeMillis();
System.out.println("whileTest: "+(b-a)+"ms");
System.out.println("LinkedList Test:");
a=System.currentTimeMillis();
cf.forTest(cf.LT);
b=System.currentTimeMillis();
System.out.println("forTest: "+(b-a)+"ms");
a=System.currentTimeMillis();
cf.foreachTest(cf.LT);
b=System.currentTimeMillis();
System.out.println("foreachTest: "+(b-a)+"ms");
a=System.currentTimeMillis();
cf.iteratorTest(cf.LT);
b=System.currentTimeMillis();
System.out.println("iteratorTest: "+(b-a)+"ms");
a=System.currentTimeMillis();
cf.whileTest(cf.LT);
b=System.currentTimeMillis();
System.out.println("whileTest: "+(b-a)+"ms");
}
}