LinkedList简介
LinkedList 是一个继承于AbstractSequentialList的双向链表。它也可以被当作堆栈、队列或双端队列进行操作
LinkedList 实现 List 接口,能对它进行队列操作
LinkedList 实现 Deque 接口,即能将LinkedList当作双端队列使用
LinkedList 实现了Cloneable接口,即覆盖了函数clone(),能克隆
LinkedList 实现java.io.Serializable接口,这意味着LinkedList支持序列化,能通过序列化去传输
LinkedList 是非同步的
LinkedList属性
public class LinkedList
extends AbstractSequentialList
implements List, Deque, Cloneable, java.io.Serializable{
//当前有多少个节点
transient int size = 0;
//第一个节点
transient Node first;
//最后一个节点
transient Node last;
}
1
2
3
4
5
6
7
8
9
10
LinkedList构造方法
/**
* Constructs an empty list.
*/
public LinkedList() {
}
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
/**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the specified
* collection's iterator. The behavior of this operation is undefined if
* the specified collection is modified while the operation is in
* progress. (Note that this will occur if the specified collection is
* this list, and it's nonempty.)
*
* @param c collection containing elements to be added to this list
* @return {@code true} if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
/**
* Inserts all of the elements in the specified collection into this
* list, starting at the specified position. Shifts the element
* currently at that position (if any) and any subsequent elements to
* the right (increases their indices). The new elements will appear
* in the list in the order that they are returned by the
* specified collection's iterator.
*
* @param index index at which to insert the first element
* from the specified collection
* @param c collection containing elements to be added to this list
* @return {@code true} if this list changed as a result of the call
* @throws IndexOutOfBoundsException {@inheritDoc}
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);
Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;
Node<E> pred, succ;
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}
for (Object o : a) {
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null);
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;
}
if (succ == null) {
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
size += numNew;
modCount++;
return true;
}
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
默认构造方法是空的,什么都没做,表示初始化的时候size为0,first和last的节点都为空:
另一个构造方法是带Collection值得对象作为入参的构造函数的,下面是执行逻辑:
使用this()调用默认的无参构造函数。
调用addAll()方法,传入当前的节点个数size,此时size为0,并将collection对象传递进去
检查index有没有数组越界的嫌疑
将collection转换成数组对象a
循环遍历a数组,然后将a数组里面的元素创建成拥有前后连接的节点,然后一个个按照顺序连起来。
修改当前的节点个数size的值
操作次数modCount自增1.
add方法
add(E e)方法
/**
* Appends the specified element to the end of this list.
*
*
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 l = last;
final Node newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
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
该方法直接将新增的元素放置链表的最后面,然后链表的长度(size)加1,修改的次数(modCount)加1
add(int index, E element)方法
/**
* Inserts the specified element at the specified position in this list.
* Shifts the element currently at that position (if any) and any
* subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
/**
* Inserts element e before non-null Node succ.
*/
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}
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
28
29
30
31
32
指定位置往数组链表中添加元素
检查添加的位置index 有没有小于等于当前的长度链表size,并且要求大于0
如果是index是等于size,那么直接往链表的最后面添加元素,相当于调用add(E e)方法
如果index不等于size,则先是索引到处于index位置的元素,然后在index的位置前面添加新增的元素。
get方法
get方法
/**
* 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;
}
}
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
28
29
30
首先是判断索引位置有没有越界,确定完成之后开始遍历链表的元素,那么从头开始遍历还是从结尾开始遍历呢,这里其实是要索引的位置与当前链表长度的一半去做对比,如果索引位置小于当前链表长度的一半,否则从结尾开始遍历
getfirst方法
/**
* Returns the first element in this list.
*
* @return the first element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getFirst() {
final Node f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
直接将第一个元素返回
getlast方法
/**
* Returns the last element in this list.
*
* @return the last element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getLast() {
final Node l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
1
2
3
4
5
6
7
8
9
10
11
12
直接将最后一个元素返回
remove方法
remove()方法
/**
* Retrieves and removes the head (first element) of this list.
*
* @return the head of this list
* @throws NoSuchElementException if this list is empty
* @since 1.5
*/
public E remove() {
return removeFirst();
}
1
2
3
4
5
6
7
8
9
10
remove方法本质调用的还是removeFirst方法(递归)
removeFirst()方法
/**
* Removes and returns the first element from this list.
*
* @return the first element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeFirst() {
final Node f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
/**
* Unlinks non-null first node f.
*/
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
final E element = f.item;
final Node<E> next = f.next;
f.item = null;
f.next = null; // help GC
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
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
28
29
30
31
32
移除第一个节点,将第一个节点置空,让下一个节点变成第一个节点,链表长度减1,修改次数加1,返回移除的第一个节点。
removeLast()方法
/**
- Removes and returns the last element from this list.
- @return the last element from this list
- @throws NoSuchElementException if this list is empty
*/
public E removeLast() {
final Node l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
/**
- Unlinks non-null last node l.
*/
private E unlinkLast(Node l) {
// assert l == last && l != null;
final E element = l.item;
final Node prev = l.prev;
l.item = null;
l.prev = null; // help GC
last = prev;
if (prev == null)
first = null;
else
prev.next = null;
size–;
modCount++;
return element;
}
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
28
29
30
31
移除最后一个节点,将最后一个节点置空,最后一个节点的上一个节点变成last节点,链表长度减1,修改次数加1,返回移除的最后一个节点。
remove(int index)方法
/**
* 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 {@inheritDoc}
*/
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
/**
* 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;
}
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
先是检查移除的位置是否在链表长度的范围内,如果不在则抛出异常,根据索引index获取需要移除的节点,将移除的节点置空,让其上一个节点和下一个节点对接起来
set方法
/**
* 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 {@inheritDoc}
*/
public E set(int index, E element) {
checkElementIndex(index);
Node x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
检查设置元素位然后置是否越界,如果没有,则索引到index位置的节点,将index位置的节点内容替换成新的内容element,同时返回旧值
clear方法
/**
* Removes all of the elements from this list.
* The list will be empty after this call returns.
*/
public void clear() {
// Clearing all of the links between nodes is “unnecessary”, but:
// - helps a generational GC if the discarded nodes inhabit
// more than one generation
// - is sure to free memory even if there is a reachable Iterator
for (Node x = first; x != null; ) {
Node next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
将所有链表元素置空,然后将链表长度修改成0,修改次数加1
push和pop方法
/**
* Pushes an element onto the stack represented by this list. In other
* words, inserts the element at the front of this list.
*
*
This method is equivalent to {@link #addFirst}.
*
* @param e the element to push
* @since 1.6
*/
public void push(E e) {
addFirst(e);
}
/**
* Pops an element from the stack represented by this list. In other
* words, removes and returns the first element of this list.
*
* <p>This method is equivalent to {@link #removeFirst()}.
*
* @return the element at the front of this list (which is the top
* of the stack represented by this list)
* @throws NoSuchElementException if this list is empty
* @since 1.6
*/
public E pop() {
return removeFirst();
}
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
push其实就是调用addFirst(e)方法,pop调用的就是removeFirst()方法
toArray方法
/**
* Returns an array containing all of the elements in this list
* in proper sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must allocate
* a new array). The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this list
* in proper sequence
*/
public Object[] toArray() {
Object[] result = new Object[size];
int i = 0;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
创建一个Object的数组对象,然后将所有的节点都添加到Object对象中,返回Object数组对象。
listIterator方法
/**
- Returns a list-iterator of the elements in this list (in proper
- sequence), starting at the specified position in the list.
- Obeys the general contract of {@code List.listIterator(int)}.
- The list-iterator is fail-fast: if the list is structurally
- modified at any time after the Iterator is created, in any way except
- through the list-iterator’s own {@code remove} or {@code add}
- methods, the list-iterator will throw a
- {@code ConcurrentModificationException}. Thus, in the face of
- concurrent modification, the iterator fails quickly and cleanly, rather
- than risking arbitrary, non-deterministic behavior at an undetermined
- time in the future.
- @param index index of the first element to be returned from the
-
list-iterator (by a call to {@code next})
- @return a ListIterator of the elements in this list (in proper
-
sequence), starting at the specified position in the list
- @throws IndexOutOfBoundsException {@inheritDoc}
- @see List#listIterator(int)
*/
public ListIterator listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
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
这个方法返回的是一个内部类ListIterator,用户可以使用这个内部类变量当前的链表元素,但是由于LinkedList也是非线程安全的类,多线程下面使用,也可能会产生多线程修改的异常。
作者:VicterTian
来源:CSDN
原文:https://blog.csdn.net/TTTZZZTTTZZZ/article/details/84928212
版权声明:本文为博主原创文章,转载请附上博文链接!