import java.util.LinkedList;
import java.util.ArrayList;
import java.util.Random;
public class TestList {
private static Random random = new Random();
public static void main(String[] args){
ArrayList<String> arraylist = new ArrayList<String>();
LinkedList<String> linkedlist = new LinkedList<String>();
for(int i=0;i<50000;i++){
String r = randomString();
arraylist.add(r);
linkedlist.add(r);
}
System.out.println("arraylist size "+arraylist.size());
System.out.println("linkedlist size "+linkedlist.size());
System.out.println("------");
long begin = System.currentTimeMillis();
for(int i=0;i<1000;i++){
for(int j=0;j<arraylist.size();j++){
String s=arraylist.get(j);
}
}
System.out.println("arraylist get(n) time "+(System.currentTimeMillis()-begin));
begin = System.currentTimeMillis();
for(int i=0;i<1000;i++){
for(String s:arraylist){
}
}
System.out.println("arraylist foreach time "+(System.currentTimeMillis()-begin));
begin = System.currentTimeMillis();
for(int i=0;i<1;i++)
for(int j=0;j<linkedlist.size();j++){
String s=linkedlist.get(j);
}
System.out.println("linkedlist get(n) time "+(System.currentTimeMillis()-begin)*1000);
begin = System.currentTimeMillis();
for(int i=0;i<1000;i++)
for(String s:linkedlist){
// linkedlist.get(j);
}
System.out.println("linkedlist foreach time "+(System.currentTimeMillis()-begin));
}
protected static String randomString() {
return Long.toString(random.nextLong(), 36);
}
}
arraylist size 50000
linkedlist size 50000
------
arraylist get(n) time 562
arraylist foreach time 1703
linkedlist get(n) time 1922000
linkedlist foreach time 813
结论linkedlist foreach比arraylist foreach快