湛蓝之海 发表于 2021-10-5 23:06:50

Java源码解析LinkedList

今天小编就为大家分享一篇关于Java源码解析LinkedList,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
本文基于jdk1.8进行分析。
linkedlist和arraylist都是常用的java集合。arraylist是数组,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;
}
}
成员变量如下。它有头节点和尾节点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循环get(i)的方式去遍历arraylist,但千万不要这样去遍历linkedlist。因为linkedlist进行get时,需要把从头结点或尾节点一个一个的找到第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。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对CodeAE代码之家的支持。如果你想了解更多相关内容请查看下面相关链接
原文链接:https://blog.csdn.net/li_canhui/article/details/85004699

http://www.zzvips.com/article/174518.html
页: [1]
查看完整版本: Java源码解析LinkedList