public static void main(String[] args) {
List<Integer> al = new ArrayList<>();
List<Integer> ll = new LinkedList<>();
int testSize = 100000;
long t0 = System.currentTimeMillis();
for(int i = 0; i < testSize; i++)
// no matter add(0) or add(index, 0)
al.add(i / 2, 0);
long t1 = System.currentTimeMillis();
System.out.println("adding data to arraylist cost:" + (t1 - t0));
for(int i = 0; i < testSize; i++)
ll.add(i / 2, 0);
long t2 = System.currentTimeMillis();
System.out.println("adding data to linkedlist cost" + (t2 - t1));
for(int i = 0; i < testSize; i++)
al.get(i);
long t3 = System.currentTimeMillis();
System.out.println("traversing all element in arraylist cost:" + (t3 - t2));
for(int i = 0; i < testSize; i++)
ll.get(i);
long t4 = System.currentTimeMillis();
System.out.println("traversing all element in linkedlist cost:" + (t4 - t3));
for(int i = testSize - 1; i > -1; i--)
al.remove(i/2);
long t5 = System.currentTimeMillis();
System.out.println("remove all element one by one from arraylist cost:" + (t5 - t4));
for(int i = testSize - 1; i > -1; i--)
ll.remove(i/2);
long t6 = System.currentTimeMillis();
System.out.println("remove all element one by one from linkedlist cost:" + (t6 - t5));
}
控制台输出:
adding data to arraylist cost:311
adding data to linkedlist cost4489
traversing all element in arraylist cost:4
traversing all element in linkedlist cost:4420
remove all element one by one from arraylist cost:334
remove all element one by one from linkedlist cost:5682我的java版本1.8.0_45,用网上1.7的编译器也是类似效果,按理说遍历操作LinkedList慢无可厚非,但添加和删除数据也慢有点令人费解。