package jiben.data;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class Listsd {
public static void main(String[] args) {
// TODO Auto-generated method stub
//添加记录是
int sum = 10000000;
//移除记录数
int rm = 300;
//修改记录数
int cha = 30000;
System.out.println("start add "+sum/10000+"W rows; rm "+300+" rows;cha "+cha+" rows");
System.out.println("--------------------------------------");
System.out.println("");
System.out.println("");
long n = System.nanoTime();
List<String> al = new ArrayList<String>();
Listsd.test(al,sum,rm,cha,n);
n = System.nanoTime();
al = new LinkedList<String>();
Listsd.test(al,sum,rm,cha,n);
}
public static void test(List<String> al,int sum,int rm,int cha,long n){
if(al instanceof ArrayList)
System.out.println("ArrayList");
else
System.out.println("LinkedList");
System.out.println("init time(ns) "+(System.nanoTime()-n));
long s = System.currentTimeMillis();
for(int i=0;i<sum;i++){
al.add("hello");
}
System.out.println("add time "+(System.currentTimeMillis()-s));
s = System.currentTimeMillis();
ListIterator<String> it = al.listIterator();
while(it.hasNext()){
it.next();
}
System.out.println("read time "+(System.currentTimeMillis()-s));
s = System.currentTimeMillis();
for(int i=0;i<cha;i++)
al.set(i, "word");
System.out.println("change rows time "+(System.currentTimeMillis()-s));
s = System.currentTimeMillis();
for(int i=0;i<rm;i++)
al.remove(i);
System.out.println("remove rows time "+(System.currentTimeMillis()-s));
s = System.currentTimeMillis();
al.clear();
System.out.println("clear time "+(System.currentTimeMillis()-s));
System.out.println("--------------------------------------");
System.out.println("");
System.out.println("");
}
}
console结果:
结论选择List的时候
start add 1000W rows; rm 300 rows;cha 30000 rows
--------------------------------------
ArrayList
init time(ns) 39822
add time 160
read time 11
change rows time 3
remove rows time 3163
clear time 12
--------------------------------------
LinkedList
init time(ns) 756210
add time 2831
read time 79
change rows time 644
remove rows time 0
clear time 66
--------------------------------------
1.如果集合特别长没有删除元素的操作,首选ArrayList.否则选择LinkedList.ArrayList删除元素耗费时间远大于LinkedList.
2.集合不是很大,选择ArrayList(init、add、read的时间很短)