Java中arraylist和linkedlist源代碼分析與性能比較
Java中arraylist和linkedlist源代碼分析與性能比較
1,簡單介紹
在java開發中比較經常使用的數據結構是arraylist和linkedlist,本文主要從源代碼角度分析arraylist和linkedlist的性能。
2,arraylist源代碼分析
Arraylist底層的數據結構是一個對象數組。有一個size的成員變量標記數組中元素的個數,例如以下圖:
* The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. */ private transient Object[] elementData; /** * The size of the ArrayList (the number of elements it contains). * * @serial */ private int size;
在構造函數中Arraylist初始化為一個長度為10的對象數組。例如以下:
/** * Constructs an empty list with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @throws IllegalArgumentException if the specified initial capacity * is negative */
public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; }
/** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this(10); }
Arraylist在添加數據時,首先推斷數組是否超過原始分配數組的長度。假設超過。則通過數組復制的形式擴大數組然後再添加數組元素。時間復雜度處於O(1)到O(n)之間。源代碼例如以下:
/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by [email protected] Collection#add}) */ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
private void ensureCapacityInternal(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); }
/** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */ private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); }
/** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). * * @param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException [email protected]} */ public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work return oldValue; }
Arraylist在改動數據時,首先推斷第i個元素是否越界,然後直接做賦值操作。時間復雜度是O(1)。
/** * Replaces the element at the specified position in this list with * the specified element. * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position * @throws IndexOutOfBoundsException [email protected]} */ public E set(int index, E element) { rangeCheck(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; }
Arraylist在獲取數據時,首先判讀第i個元素是否越界,然後獲取對象數組中的第i個元素時間復雜度是O(1)。源代碼例如以下圖:
/** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException [email protected]} */ public E get(int index) { rangeCheck(index); return elementData(index); }
3,linkedlist源代碼分析
Linkedlist的用到的底層數據結構是雙向鏈表,數據結構例如以下圖:
private static class Node<E> { E item; Node<E> next; Node<E> prev; Node(Node<E> prev, E element, Node<E> next) { this.item = element; this.next = next; this.prev = prev; } }
Linkedlist的成員變量主要有三個,size表示鏈表的長度,first指向鏈表的頭部,last指向鏈表的尾部,源代碼例如以下圖:
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable { transient int size = 0; /** * Pointer to first node. * Invariant: (first == null && last == null) || * (first.prev == null && first.item != null) */ transient Node<E> first; /** * Pointer to last node. * Invariant: (first == null && last == null) || * (last.next == null && last.item != null) */ transient Node<E> last;
Linkedlist的添加操作。僅僅是在鏈表的尾部添加一個節點,時間復雜度是O(1)。源代碼例如以下圖:
/** * Appends the specified element to the end of this list. * * <p>This method is equivalent to [email protected] #addLast}. * * @param e element to be appended to this list * @return [email protected] true} (as specified by [email protected] Collection#add}) */ public boolean add(E e) { linkLast(e); return true; }
/** * Links e as last element. */ 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++; }
Linkedlist的刪除操作。首先推斷刪除的位置是否越界。然後找到第i個元素,最後刪除第一個元素,由於在刪除的時候要依據元素的位置獲取元素,所以時間復雜度是O(N)。源代碼例如以下:
/** * Removes the element at the specified position in this list. Shifts any * subsequent elements to the left (subtracts one from their indices). * Returns the element that was removed from the list. * * @param index the index of the element to be removed * @return the element previously at the specified position * @throws IndexOutOfBoundsException [email protected]} */ public E remove(int index) { checkElementIndex(index); return unlink(node(index)); }
</pre><pre code_snippet_id="1635127" snippet_file_name="blog_20160405_24_2093084" name="code" class="java"> /** * Returns the (non-null) Node at the specified element index. */ Node<E> node(int index) { // assert isElementIndex(index); if (index < (size >> 1)) { Node<E> x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { Node<E> x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } }
/** * Unlinks non-null node x. */ E unlink(Node<E> x) { // assert x != null; final E element = x.item; final Node<E> next = x.next; final Node<E> prev = x.prev; if (prev == null) { first = next; } else { prev.next = next; x.prev = null; } if (next == null) { last = prev; } else { next.prev = prev; x.next = null; } x.item = null; size--; modCount++; return element; }
Linkedlist的改動操作。首先是推斷數組是否越界。然後獲取當前位置的元素。最後做改動操作,因為在獲取當前位置的元素時,須要遍歷鏈表。所以時間復雜度是O(N),源代碼例如以下:
/**
* Replaces the element at the specified position in this list with the * specified element. * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position * @throws IndexOutOfBoundsException [email protected]} */ public E set(int index, E element) { checkElementIndex(index); Node<E> x = node(index); E oldVal = x.item; x.item = element; return oldVal; }
/** * Returns the (non-null) Node at the specified element index. */ Node<E> node(int index) { // assert isElementIndex(index); if (index < (size >> 1)) { Node<E> x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { Node<E> x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } }
Linkedlist的獲取元素操作。首先是推斷數組是否越界,然後獲取當前位置的元素,因為在獲取當前位置的元素時,須要遍歷鏈表,所以時間復雜度是O(N),源代碼例如以下:
/** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException [email protected]} */ public E get(int index) { checkElementIndex(index); return node(index).item; }
/** * Returns the (non-null) Node at the specified element index. */ Node<E> node(int index) { // assert isElementIndex(index); if (index < (size >> 1)) { Node<E> x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { Node<E> x = last; for (int i = size - 1; i > index; i--) x = x.prev; return x; } }
4。arraylist和linkedlist的效率分析
|
Add() |
Remove(int i) |
Set(int i, E e) |
Get(int i) |
Arraylist |
O(1)-O(N) |
O(N) |
O(1) |
O(1) |
Linkedlist |
O(1) |
O(N) |
O(N) |
O(N) |
Java中arraylist和linkedlist源代碼分析與性能比較