ArrayList和LiinkedList的区别
1、相同点
都是单列集合中List接口的实现类,存取有序,有索引,可以重复
2、不同点
底层实现不同:
ArrayList的源码:
public ArrayList(Collection<? extends E> c) { Object[] a = c.toArray(); //数组 if ((size = a.length) != 0) { if (c.getClass() == ArrayList.class) { elementData = a; } else { elementData = Arrays.copyOf(a, size, Object[].class); } } else { // replace with empty array. elementData = EMPTY_ELEMENTDATA; } }
LinkedList的源码:
public boolean addAll(int index, Collection<? extends E> c) { //双向循环链表 checkPositionIndex(index); Object[] a = c.toArray(); int numNew = a.length; if (numNew == 0) return false; Node<E> pred, succ; if (index == size) { succ = null; pred = last; } else { succ = node(index); pred = succ.prev; } for (Object o : a) { @SuppressWarnings("unchecked") E e = (E) o; Node<E> newNode = new Node<>(pred, e, null); if (pred == null) first = newNode; else pred.next = newNode; pred = newNode; } if (succ == null) { last = pred; } else { pred.next = succ; succ.prev = pred; } size += numNew; modCount++; return true; } private static class Node<E> { //node E item; Node<E> next; //next指针 Node<E> prev; //前驱指针 Node(Node<E> prev, E element, Node<E> next) { this.item = element; this.next = next; this.prev = prev; } }
ArrayList的底层实现是数组,LinkedList底层是双向链表,有头尾指针。
ArrayList查询快,增删慢
-
查询快:数组随机访问,通过数组地址和元素索引计算出元素地址进行访问 增删慢:增删不在尾部,都需要移动元素,如果数组容量不足需要扩容。ArrayList有扩容机制。 扩容机制: 分配一个原数组1.5倍大小的新数组 将原数组的内容拷贝到新数组
LinkedList查询慢,增删快
-
查询慢:从头或尾依次寻址 增删快:只需要修改几个指针的指向
所以结论:
-
当业务中增删频繁的时候,使用LinkedList 当业务中查询频繁的时候,使用ArrayList
下一篇:
数据库习题(六):关系数据理论