好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java源码解析LinkedList

本文基于jdk1.8进行分析。

linkedlist和arraylist都是常用的java集合。arraylist是数组,linkedlist是链表,是双向链表。它的节点的数据结构如下。

?

1

2

3

4

5

6

7

8

9

10

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个指针。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

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方式。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

/**

  * 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方法把待添加的元素添加到链表末尾即可。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

/**

  * 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。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/li_canhui/article/details/85004699

查看更多关于Java源码解析LinkedList的详细内容...

  阅读:11次