As early as sophomore java foundation courses, we will have some insight into the:
LinkedList 1.
2. ArrayList
then both what similarities and differences do
first is to test the code:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import bean.Answer;
import bean.User;
/**
* 测试类
*
* @author hxz
*
*/
public class MyTestUtil {
public static void addTest(List<String> list) {
System.out.println(list.getClass().getName() + "开始查询");
long start = System.currentTimeMillis();
System.out.println("开始时间:" + start);
list.add("需要查找的数据");
list.add("eeee");
list.add("aaee");
list.add("abbb");
for (int i = 0; i < 10000000; i++) {
for (int j = 0; j < list.size(); j++) {
list.get(j).contains("e");
System.out.print("");
}
}
long end = System.currentTimeMillis();
System.out.println("结束时间:" + end);
System.out.println("总耗时:" + (end - start));
}
public static void main(String[] args) {
List<String> a = new ArrayList<>();
List<String> b = new LinkedList<>();
addTest(a);
addTest(b);
}
}
? ? ? Not to say ArrayList queries faster than LinkedList it?
然后我们测试增加
???简直颠覆我的认知!
难道我学的都是错的吗?
事情的真相只有一个!
首先我们需要了解
linkedLIst是双向链表结构
元素之间的所有关系是通过引用关联的,就好比最近特别火的从袖子里撤出棒棒糖来的情景,想要撤出下一个就必须撤出上一个。它在查询的时候,只能一个一个的遍历查询,所以他的查询效率很低,如果我们想删除一节怎么办呢?就相当于自行车的链子,有一节坏了,我们是不是直接把坏的那节仍掉,然后让目标节的上一节指向目标节的下一节,但是
ArrayList是数组结构
就是有相同特性的一组数据的箱子,比如说我有一个能容下10个苹果的箱子,我现在只放了5个苹果,那么放第6个是不是直接放进去就行了?呢我要放11个呢?这个箱子是不是放不下了?所以我是不是需要换个大点的箱子?这就是**数组的扩容!**同样,我们一般放箱子里面的东西是不是按照顺序放的?假如说是按abcd的顺序放的,我突然想添加一个e,这个e要放到c的后面,你是不是需要把d先拿出来,再把e放进去,再把d放进去?假如说c后面有10000个呢?你是不是要把这10000个都拿出来,把e放进去,再放这10000个?效率是不是很低了?所以,理论上它的增删比较慢!但是前面也说了,我们箱子里面放东西,都是按照顺序放的,所以我知道其中一个"地址",是不是就知道所有元素的地址?所以它的查询在理论上比较快!
注意:只是在在list容量较大情况下,ArrayList查询数据要远优于LinkedList
Summary
ArrayList and LinkedList advantages and disadvantages in performance, have their own local applicable, in general be described as follows:
for ArrayList, the main one is the increase in the internal array of data, point to the added element, occasionally complexity is O (n) may lead to an array of re-allocation; while LinkedList is concerned, this is a unified overhead, complexity is O (1), assign an internal object.
Inserting or deleting an element in the middle of the ArrayList means that the remaining elements in the list will be moved; and inserting or deleting an element in the middle of LinkedList cost is fixed.
- LinkedList does not support efficient random access elements.
- Just in case capacity in the larger list, ArrayList query data is much better than LinkedList