Android面试篇之ArrayList和LinkedList的区别
2017-12-17 13:47
417 查看
● 数据结构
ArrayList基于动态数组;LinkedList基于链表● 随机访问
ArrayList优于LinkedList,因为LinkedList要移动指针来查找,下面以get方法为例//ArrayList的get方法,直接从数组中获取元素值 public E get(int index) { if (index < 0 || index >= this.size) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); if (ArrayList.this.modCount != this.modCount) throw new ConcurrentModificationException(); return (E) ArrayList.this.elementData[offset + index]; } //LinkedList的get方法,node方法用来进行查找 public E get(int index) { checkElementIndex(index); return node(index).item; } Node<E> node(int index) { if (index < (size >> 1)) {//若index小于size的一半,则从头开始查找 Node<E> x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else {//若index大于size的一半,则从末尾向前开始查找 Node<E> x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } }
● 插入删除
1. 末尾插入,两个的时间复杂度都是O(1),所以差不多 [删除操作也同理]//ArrayList的add方法 public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } //LinkedList的add方法 public boolean add(E e) { linkLast(e); return true; } void linkLast(E e) { final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; }
2. 中间插入,时间复杂度也都是O(n),所以也差不多 [删除操作也同理]
//ArrayList的add方法 public void add(int index, E element) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); ensureCapacityInternal(size + 1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index);//index后面的元素后移,时间复杂度O(n) elementData[index] = element; size++; } //LinkedList的add方法 public void add(int index, E element) { checkPositionIndex(index); if (index == size) //index等于size时,直接链接到末尾 linkLast(element); else //否则直接将element链接到node(index)前面,node(index)的时间复杂度也是O(n) linkBefore(element, node(index)); } void linkLast(E e) { final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; } void linkBefore(E e, Node<E> succ) { // assert succ != null; final Node<E> pred = succ.prev; final Node<E> newNode = new Node<>(pred, e, succ); succ.prev = newNode; if (pred == null) first = newNode; else pred.next = newNode; size++; modCount++; }
相关文章推荐
- ArrayList,Vector与LinkedList的区别.
- ArrayList和LinkedList的大致区别
- LinkedList和ArrayList的区别 (转)
- ARRAYLIST VECTOR LINKEDLIST 区别与用法
- LinkedList ArrayList Vector的区别
- 集合-Arraylist和LinkedList的区别
- ArrayList和LinkedList各自实现和区别
- ArrayList和LinkedList底层实现的区别
- 关于LinkedList和ArrayList的执行效率的问题的区别(测试用例)
- 源码剖析——ArrayList和LinkedList的区别
- ArrayList Vector LinkedList 区别与用法
- 深入理解ArrayList 和 LinkedList 区别
- ARRAYLIST VECTOR LINKEDLIST 区别与用法
- ArrayList 和 linkedlist的区别
- ArrayList、LinkedList和Vector 的区别
- Java中ArrayList和LinkedList区别
- ArrayList与LinkedList的区别
- java中ArrayList和LinkedList的区别
- ArrayList和LinkedList的区别
- Java中ArrayList和LinkedList区别