Java源碼解析LinkedList
本文基于jdk1.8進行分析。
LinkedList和ArrayList都是常用的java集合。ArrayList是數(shù)組,Linkedlist是鏈表,是雙向鏈表。它的節(jié)點的數(shù)據(jù)結(jié)構(gòu)如下。
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; } }
成員變量如下。它有頭節(jié)點和尾節(jié)點2個指針。
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;
下面看一下主要方法。首先是get方法。如下圖。鏈表的get方法效率很低,這一點需要注意,也就是說,我們可以用for循環(huán)get(i)的方式去遍歷ArrayList,但千萬不要這樣去遍歷Linkedlist。因為Linkedlist進行g(shù)et時,需要把從頭結(jié)點或尾節(jié)點一個一個的找到第i個元素,效率很低。遍歷LinkedList時應(yīng)該使用foreach方式。
/** * 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 {@inheritDoc} **/ 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; } }
下面是add方法,add方法把待添加的元素添加到鏈表末尾即可。
/** * Appends the specified element to the end of this list. * <p>This method is equivalent to {@link #addLast}. * @param e element to be appended to this list * @return {@code true} (as specified by {@link 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++; }
This is the end。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
Java多線程通訊之wait,notify的區(qū)別詳解
這篇文章主要介紹了Java多線程通訊之wait,notify的區(qū)別詳解,非常不錯,具有一定的參考借鑒借鑒價值,需要的朋友可以參考下2018-07-07Spring學(xué)習(xí)筆記之RedisTemplate的配置與使用教程
這篇文章主要給大家介紹了關(guān)于Spring學(xué)習(xí)筆記之RedisTemplate配置與使用的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用spring具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-06-06關(guān)于SpringBoot整合Canal數(shù)據(jù)同步的問題
大家都知道canal是阿里巴巴旗下的一款開源工具,純java開發(fā),支持mysql數(shù)據(jù)庫,本文給大家介紹SpringBoot整合Canal數(shù)據(jù)同步的問題,需要的朋友可以參考下2022-03-03