Comparison of advantages and disadvantages of ArrayList and LinkedList
1.ArrayList implements a data structure based on a dynamic array, and LinkedList is based on a linked list data structure.
ArrayList is a data structure based on dynamic arrays.
The bottom layer of LinkedList is the structure of doubly linked list.
2. For random access get and set, ArrayList is better than LinkedList, because LinkedList needs to move the pointer.
3. For add and remove operations, LinedList has an advantage because ArrayList needs to move data.
4. When traversing data, we can use iterators to traverse data
public static void main(String[] args) {
//编程实现证明ArrayList和LinkedList优缺点
int zs = 0;
Random r = new Random();
ArrayList<Integer> alist = new ArrayList<>();
LinkedList<Integer> llist = new LinkedList<>();
long ss = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
alist.add(0, r.nextInt(1, 41));
//由于时间过长,这样可以查看已完成进度
if (i % 1000 == 0) {
System.out.println("已完成" + i);
}
}
long ee = System.currentTimeMillis();
System.out.println(ee - ss);
ss = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
llist.add(0, r.nextInt(1, 41));
}
ee = System.currentTimeMillis();
System.out.println(ee - ss);
//ArrayList遍历
ss = System.currentTimeMillis();
for (Integer a : alist) {
zs = a;
}
ee = System.currentTimeMillis();
System.out.println("ArrayList遍历:" + (ee - ss));
//LinkedList遍历
ss = System.currentTimeMillis();
for (Integer a : llist) {
zs = a;
}
ee = System.currentTimeMillis();
System.out.println("LinkedList遍历:" + (ee - ss));
//ArrayList遍历使用迭代器
ss = System.currentTimeMillis();
Iterator<Integer> ita = alist.listIterator();
while (ita.hasNext()) {
zs = ita.next();
}
ee = System.currentTimeMillis();
System.out.println("ArrayList遍历使用迭代器:" + (ee - ss));
//LinkedList遍历使用迭代器
ss = System.currentTimeMillis();
Iterator<Integer> itl = alist.listIterator();
while (itl.hasNext()) {
zs = itl.next();
}
ee = System.currentTimeMillis();
System.out.println("LinkedList遍历使用迭代器:" + (ee - ss));
}
The result of the operation is shown in the figure