Java源碼解析LinkedList
本文基于jdk1.8進行分析。
LinkedList和ArrayList都是常用的java集合。ArrayList是數(shù)組,Linkedlist是鏈表,是雙向鏈表。它的節(jié)點的數(shù)據(jù)結構如下。
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進行get時,需要把從頭結點或尾節(jié)點一個一個的找到第i個元素,效率很低。遍歷LinkedList時應該使用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。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章
Java使用Graphics2D實現(xiàn)字符串文本自動換行
這篇文章主要為大家詳細介紹了Java如何使用Graphics2D實現(xiàn)字符串文本自動換行,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-04-04
在SpringBoot項目中使用Java8函數(shù)式接口的方法示例
在Spring Boot項目中,Java 8 的函數(shù)式接口廣泛用于實現(xiàn)各種功能,如自定義配置、數(shù)據(jù)處理等,函數(shù)式接口在Spring Boot中非常有用,本文展示了在SpringBoot項目中使用Java8的函數(shù)式接口的方法示例,需要的朋友可以參考下2024-03-03
IDEA中Maven報錯Cannot resolve xxx的解決方法匯總(親測有效)
在IDEA中的pom文件中添加了依賴,并且正確加載了相應依賴,pom文件沒有報紅,看起來像是把所有依賴庫全部加載進來了,但是代碼中使用依賴的類庫使報紅,本文給大家介紹了IDEA中Maven報錯Cannot resolve xxx的解決方法匯總,需要的朋友可以參考下2024-06-06
Intellij IDEA中啟動多個微服務(開啟Run Dashboard管理)
這篇文章主要介紹了Intellij IDEA中啟動多個微服務(開啟Run Dashboard管理),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07

