ArrayList和LinkedList的区别
作者:互联网
经常看到的观点:
ArrayList查询快,增删改慢
LinkedList查询慢,增删改快
先看下面demo代码:
public static void main(String[] args) {
int n = 1000;
int insertIndex = n;
for (int i = 0; i < 1; i++) {
//randomArray生面随机数组,这里意思是1000个随机数
int[] array = randomArray(n);
List<Integer> list1 =
Arrays.stream(array).boxed().collect(Collectors.toList());
LinkedList<Integer> list2 = new LinkedList<>(list1);
addFirst(list1,list2);
addMiddle(list1, list2, n / 2);
addLast(list1,list2);
arrayListSize((ArrayList<Integer>) list1);
linkedListSize(list2);
}
}
private static void addMiddle(List<Integer> list1, LinkedList<Integer> list2, int mid) {
StopWatch sw = new StopWatch();
sw.start("ArrayList");
list1.add(mid, 100);
sw.stop();
sw.start("LinkedList");
list2.add(mid, 100);
sw.stop();
System.out.println(sw.prettyPrint());
}
private static void addFirst(List<Integer> list1, LinkedList<Integer> list2) {
StopWatch sw = new StopWatch();
sw.start("ArrayList");
list1.add(0, 100);
sw.stop();
sw.start("LinkedList");
list2.addFirst(100);
sw.stop();
System.out.println(sw.prettyPrint());
}
private static void addLast(List<Integer> list1, LinkedList<Integer> list2) {
StopWatch sw = new StopWatch();
sw.start("ArrayList");
list1.add(100);
sw.stop();
sw.start("LinkedList");
list2.add(100);
sw.stop();
System.out.println(sw.prettyPrint());
}
执行往头部addFirst插入的运行截图如下:LinkedList的效率比ArrayList的效率好很多
Connected to the target VM, address: '127.0.0.1:59369', transport: 'socket'
StopWatch '': running time = 81898 ns
---------------------------------------------
ns % Task name
---------------------------------------------
000073599 090% ArrayList
000008299 010% LinkedList
Disconnected from the target VM, address: '127.0.0.1:59369', transport: 'socket'
Process finished with exit code 0
执行往中间addMiddle插入的运行结果:
Connected to the target VM, address: '127.0.0.1:62319', transport: 'socket'
StopWatch '': running time = 5230109099 ns
---------------------------------------------
ns % Task name
---------------------------------------------
1677949199 032% ArrayList
3552159900 068% LinkedList
往最后插入运行截图:
ns % Task name
---------------------------------------------
000027600 087% ArrayList
000004200 013% LinkedList
往中间插入元素的时候,LinkedList并不是很快,因为LinkedList也要循环找到中间那个位置在插入。头和尾插入挺快的
标签:LinkedList,区别,sw,ArrayList,list1,list2,StopWatch 来源: https://blog.csdn.net/weixin_43075758/article/details/121445796