在刚学java的时候,就有一个知识点说关于 arrayList 和 linkedList之前的区别。
那就是他们的数据接口不同,一个是数组,一个是链表。
所以一个适合查找,一个是适合修改,这也是面试的时候常考的内容。
但是最近我听别人说并不是这样,所以准备自己也试试看。
先初始化两个链表
int elementCount = 100000;
int loopCount = 100000;
LinkedList linkedlist = IntStream.rangeClosed(1, elementCount).boxed().collect(Collectors.toCollection(LinkedList::new));
ArrayList arrayList = IntStream.rangeClosed(1, elementCount).boxed().collect(Collectors.toCollection(ArrayList::new));
首先先试试查找
//LinkedList访问
private static void linkedListGet(LinkedList list,int loopCount,int elementCount) {
IntStream.rangeClosed(1, loopCount).forEach(i -> list.get(ThreadLocalRandom.current().nextInt(elementCount)));
}
//ArrayList访问
private static void arrayListGet(ArrayList list,int loopCount,int elementCount) {
IntStream.rangeClosed(1, loopCount).forEach(i -> list.get(ThreadLocalRandom.current().nextInt(elementCount)));
}
然后执行查看
StopWatch stopWatch = new StopWatch();
stopWatch.start("linkedListGet");
linkedListGet(linkedlist, loopCount,elementCount);
stopWatch.stop();
stopWatch.start("arrayListGet");
arrayListGet(arrayList, loopCount,elementCount);
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
=[Spring MX]= XMX Agent 0.4.1 is started using configuration in C:\Users\wxk\.IdeaIC2019.3\config\plugins\smx-idea\lib\xmx\smx.ini
=[Spring MX]= Logging INFO events to ${user.home}/.xmx/logs/
=[Spring MX]= Web console will be started at http://localhost:8081/smx/ in ~10 seconds
StopWatch '': running time (millis) = 5013
-----------------------------------------
ms % Task name
-----------------------------------------
05007 100% linkedListGet
00006 000% arrayListGet
看得出来,查找方面差距很大,相差近千倍,没啥好说的
再看看插入
//LinkedList插入
private static void linkedListAdd(LinkedList list, int loopCount,int elementCount) {
IntStream.rangeClosed(1, loopCount).forEach(i -> list.add(ThreadLocalRandom.current().nextInt(elementCount), 1));
}
//ArrayList插入
private static void arrayListAdd(ArrayList list, int loopCount,int elementCount) {
IntStream.rangeClosed(1, loopCount).forEach(i -> list.add(ThreadLocalRandom.current().nextInt(elementCount), 1));
}
StopWatch stopWatch2 = new StopWatch();
stopWatch2.start("linkedListAdd");
linkedListAdd(linkedlist, loopCount,elementCount);
stopWatch2.stop();
stopWatch2.start("arrayListAdd");
arrayListAdd(arrayList, loopCount,elementCount);
stopWatch2.stop();
System.out.println(stopWatch2.prettyPrint());
=[Spring MX]=
=[Spring MX]= Web console is successfully started at http://localhost:8081/smx/
=[Spring MX]=
StopWatch '': running time (millis) = 49263
-----------------------------------------
ms % Task name
-----------------------------------------
46748 095% linkedListAdd
02515 005% arrayListAdd
这虽然没有上面那么明显,但是我们还是看得出来,差了二十多呗,数组链表并没有想象中这么多。
原因是因为,源码中链表在插入的时候还是有前面一段查找节点的时间,所以这个方面linkedList就差太多了。