LinkedList 继承了AbstractSequentialList类
实现了 List<E>, Deque<E>, Cloneable, java.io.Serializable接口
LinkedList 顾名思义 一个链式的表。那么底层数据结构就是一个链表维护的。这个链表的单元就是一个一个节点。下面来分析LinkedList的节点。
Node节点内部类
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;
}
}
熟悉C/C++的人,对这个形式并不陌生。这是定义链表的必经之路,只不过这里是一个内部类,而不是结构体。
在节点类中,定义了节点对象保存的数据,以及它的前驱和后继。由此可见LinkedList中,是由双向链表进行底层数据维护。
属性
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;
在LinkedList中 有三个比较重要的属性。 size 标识当前List的大小,
first 表示当前List的头节点。恒等式(first == null && last == null) || (first.prev == null && first.item != null)
last 表示当前List的末节点。恒等式(first == null && last == null) || (last.next == null && last.item != null)
构造方法
空的构造方法
构造一个空的LinkedList
/**
* Constructs an empty list.
*/
public LinkedList() {
}
利用一个已知集合构造方法
这个构造方法是利用一个已有的集合进行构造。但是有一个约束条件,即这个集合中的元素要是当前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);
}
构造方法首先调用了本类的一个公有方法,用于从集合中添加数据到当前LinkedList。
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
这个方法调用了另一个重载的方法,它的第一个参数标志插入的位置。此处用的是size, 也就是说是在当前集合的末尾
插入方法
addAll(int index, Collection<? extends E> 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;
}
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
(1)checkPositionIndex 是用来检测index是否合法。实现方法也很简单,只需判断
<span style="font-size:18px;">index >= 0 && index <= size</span>
(2)构造了一个数组,把Collection转换为对象数组,如果这个数组为空,那么直接返回false 。插入失败。
(4)判断要插入的位置在哪。如果是size,即末尾,那么让succ为空,pred指向尾节点。否则succ指向插入的位置,pred指向插入的位置前一个节点。
(5) 遍历对象数组,每次取一个对象构造一个新的节点,并将这个节点的前驱节点置为pred。如果pred是空,则这个新的节点就是LinkedList的头节点,否则让pred的后继节点为nexNode,pred指向newNode.这一步是所有链表插入的通用步骤,很好理解。而且这种插入仅仅是通过移动指针实现的,所以说LinkedList在需要插入大量元素的时候,效率是很高的
(6) 最后是处理末节点指针指向。如果这个插入动作是在原列表的末尾插入,那么pred就是最后尾节点.last指针指向这个位置,否则就让pred与succ连接上。这里才理解succ的作用,它就好像粘合剂一样,插入的时候,把原来的列表从它这个地方断开,在插入完成的时候,又从这个地方粘上。
(7)插入工作完成,modCount++。这个变量保证LinkedList的一致性。
add(E e)
在LinkedList 末尾插入新的元素,它的实现实际用到linkLast(E e)方法
public boolean add(E e) {
linkLast(e);
return true;
}
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++;
}
linkLast 用于将元素插入到LinkedList的末尾,它是实现与addAll中的代码类似。个人觉得应该复用
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));
}
这个方法首先检查要插入的位置是否为链表的末尾,如果是,直接调用来末尾插入的方法linkLast ,否则执行linkBefore代码,即在某个元素之前插入。在此处共调用了两个方法,node(int index)和linkBefore(E e, Node<E> succ)。下面来看源码
node(int 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;
}
}
看这个代码的名字,基本也就可以知道这个方法是用来返回指定位置的元素的。与LinkedList类似的ArrayList也有类似的方法,名称为get。
看到这个源码,我们就能看出来LinkedList为什么要采用双向链表了,当使用双向链表的时候,可以进行折半查找了。源码中,if (index < (size >> 1)) 采用了size右移一位的操作,实际上就是在比较需要的元素的位置是在前半部分还是后半部分,如果在前面,就从first向后遍历,如果在后半呢,从last向前遍历,这样做当然是为了节省时间的。在这也可以看出,如果使用LinkedList进行查找的话,是比较消耗时间的。
linkBefore(E e, Node<E> 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++;
}
这个方法是在指定元素前面插入元素,这个方法很简单。就是获取到当前位置的前一个节点,然后构造了一个新插入的节点,把新的结点链接进来。
addFirst addLast
这两个方法分别用来在链表的头和尾插入元素,他们的实现分别采用了linkFirst和linkLast方法。这两个方法是私有方法,在此也可以理解为工具方法。
/**
* Links e as first element.
*/
private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}
/**
* 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++;
}
对比着看两个源代码,在关键的步骤都是相反的。实际上完成的是相似的工作。
push(E e)
在首节点前插入一个元素。源自于Deque,1.6版本开始
/**
* Pushes an element onto the stack represented by this list. In other
* words, inserts the element at the front of this list.
*
* <p>This method is equivalent to {@link #addFirst}.
*
* @param e the element to push
* @since 1.6
*/
public void push(E e) {
addFirst(e);
}
offer(E e)
插入一个元素到尾节点,源自于Queue,1.5版本开始
/**
* Adds the specified element as the tail (last element) of this list.
*
* @param e the element to add
* @return {@code true} (as specified by {@link Queue#offer})
* @since 1.5
*/
public boolean offer(E e) {
return add(e);
}
offerFirst(E e)
在首节点前插入一个元素。源自于Deque,1.6版本开始
/**
* Inserts the specified element at the front of this list.
*
* @param e the element to insert
* @return {@code true} (as specified by {@link Deque#offerFirst})
* @since 1.6
*/
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
offerLast(E e)
插入一个元素到尾节点,源自于Dequeue,1.6版本开始
/**
* Inserts the specified element at the end of this list.
*
* @param e the element to insert
* @return {@code true} (as specified by {@link Deque#offerLast})
* @since 1.6
*/
public boolean offerLast(E e) {
addLast(e);
return true;
}
插入模式总结
LinkedList的所有插入操作都可以总结为这样一个模式:
(1) 声明一个节点pre指向要插入位置的前一个结点,(在头尾插入的话,就指向头、尾)
(2)新建一个节点now保存要插入的元素,并将now的pre指定为pre.pre,next指定为pre。如果在链表头插入,pre为null,如果在链表尾部插入,next为null。
(3)pre.next=now
删除方法
remove()
删除LinkedList第一个结点,它的实现是利用removFirst实现
/**
* 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();
}
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<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
这个方法使用的是unlinkFirst(Node<E> f)这个工具方法来实现的。
unlinkFirst(Node<E> 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;
}
这个方法首先使用element保存当前头结点的值,因为最后要将这个值返回。然后获得了当前头结点的后继节点next,让first指针指向next节点,如果此时next为null,那么就说明当前LinkedList为空,就把last置空,否则让next节点的前驱为null。
removeLast()
删除LinkedList的最后一个元素并返回,它的实现依赖于私有方法unlinkLast
/**
* 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<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
unlinkLast(Node<E> l)
<span style="font-size:18px;">/**
* Unlinks non-null last node l.
*/
private E unlinkLast(Node<E> l) {
// assert l == last && l != null;
final E element = l.item;
final Node<E> 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;
}</span>
这个方法与前面的unlinkFirst可以对照着看,只是把first该为last,next改为prev,其他的都是一样。
remove(int index)
删除指定位置的节点。它的实现使用了工具方法unlink
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
unlink(Node<E> 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;
}
看源码很好理解,其实就是在哪删除,就把链表从哪断开,再把这个位置的前后节点”接“在一起。
首先记录删除节点的element值,用于返回。分别声明next、prev指向当前结点的next、prev。
如果prev为空,说明当前删除的节点为头节点,让first指针指向next,否则prex.next=next,当前节点的前驱结点为空。
如果next为空,说明当前删除的节点为尾节点,让last指针指向prev,否则next.prev=prev,当前节点的后继结点为空。
最后把当前节点x置空,方便GC工作。
remove(Object o)
删除第一个与Object 等价的节点
/**
* Removes the first occurrence of the specified element from this list,
* if it is present. If this list does not contain the element, it is
* unchanged. More formally, removes the element with the lowest index
* {@code i} such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns {@code true} if this list
* contained the specified element (or equivalently, if this list
* changed as a result of the call).
*
* @param o element to be removed from this list, if present
* @return {@code true} if this list contained the specified element
*/
public boolean remove(Object o) {
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
首先判断是否为null,然后遍历Linkedlist,如果存在与object相等的元素,删除,并返回。从这可以看出,LinkedList中可以包含item为null的元素,也可以存在重复的元素
removeFirstOccurrence(Object o)
删除满足条件的第一个元素,这个方法实际上就是remove(Objec o) 这个方法,从源码的方法的注释可以看出,这个方法从1.6版本开始出现。应该是Java 开发者认为应该命名一个更能说明方法作用的方法作为remove方法的替代。的确,如果不看源码的话,很容易忽略掉remove 只删除第一个元素这个特点。
/**
* Removes the first occurrence of the specified element in this
* list (when traversing the list from head to tail). If the list
* does not contain the element, it is unchanged.
*
* @param o element to be removed from this list, if present
* @return {@code true} if the list contained the specified element
* @since 1.6
*/
public boolean removeFirstOccurrence(Object o) {
return remove(o);
}
removeLastOccurrence(Object o)
删除满足条件的最后一个元素。这个方法也是在1.6版本以后才有的
/**
* Removes the last occurrence of the specified element in this
* list (when traversing the list from head to tail). If the list
* does not contain the element, it is unchanged.
*
* @param o element to be removed from this list, if present
* @return {@code true} if the list contained the specified element
* @since 1.6
*/
public boolean removeLastOccurrence(Object o) {
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
这个方法可以看成是remove(Object o) 或者 removeFirstOccurrence(Object o)的倒序版本,实际上从完成的功能来看,这个就是从尾节点向前遍历,找到objcet并删除。
poll()
删除第一个元素,从1.5版本开始。这个方法源自于Deque。
/**
* Retrieves and removes the head (first element) of this list.
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
pollFirst()
删除第一个元素,从1.6版本开始。这个方法名是poll()方法的演进版本,源码并无区别,这个方法源自于Deque
/**
* Retrieves and removes the first element of this list,
* or returns {@code null} if this list is empty.
*
* @return the first element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
public E pollFirst() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
pollLast()
删除最后一个元素,从1.6版本开始。这个方法源自于Deque
/**
* Retrieves and removes the last element of this list,
* or returns {@code null} if this list is empty.
*
* @return the last element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
public E pollLast() {
final Node<E> l = last;
return (l == null) ? null : unlinkLast(l);
}
pop()
删除第一个元素,从1.6版本开始。这个方法源自于Deque
/**
* 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();
}
修改元素
set(int index, E element)
用element替换指定位置的元素
<span style="font-size:18px;">/**
* 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<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}</span>
查看元素(element)
get(int index)
查看指定位置的元素
/**
* 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;
}
getFirst()
查看Linked头结点的元素
/**
* 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<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
如果首节点为空 抛出异常
getLast()
查看LinedList尾节点
/**
* 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<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
如果为空,抛出异常。
peek()
查看LinkedList首节点,这个方法源于Queue。1.5版本开始
/**
* Retrieves, but does not remove, the head (first element) of this list.
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
peekFirst()
查看第一个元素,这个方法源于Deque。1.6版本开始
/**
* Retrieves, but does not remove, the first element of this list,
* or returns {@code null} if this list is empty.
*
* @return the first element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
public E peekFirst() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
peekLast()
查看最后一个元素,这个方法源于Deque。1.6版本开始
/**
* Retrieves, but does not remove, the last element of this list,
* or returns {@code null} if this list is empty.
*
* @return the last element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
public E peekLast() {
final Node<E> l = last;
return (l == null) ? null : l.item;
}
clear() 清空方法
清空LinkedList的全部节点
/**
* 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<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}
对于一个链表来说,实际上只要将首、末节点置null,就可以保证整个链表已经“找不到了”。
但是这个方法显然更复杂一些,从注释看出,这里面是为了让GC尽快的回收链表中的节点,所以它遍历了整个链表,把每个节点的赋值为null。最后再把首、尾节点赋值null。
clone() 克隆方法
clone一个linkedlist的拷贝,与ArrayList一样这同样是一个浅拷贝。克隆得到的linkedlist与原linkedlist享有同一个存储空间。
public Object clone() {
LinkedList<E> clone = superClone();
// Put clone into "virgin" state
clone.first = clone.last = null;
clone.size = 0;
clone.modCount = 0;
// Initialize clone with our elements
for (Node<E> x = first; x != null; x = x.next)
clone.add(x.item);
return clone;
}
@SuppressWarnings("unchecked")
private LinkedList<E> superClone() {
try {
return (LinkedList<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
clone方法首先通过Oject方法得到一个新的linkedlist,然后依次遍历当前linkedlist,把值依次赋值给新的linkedlist。在这一步,如果要实现深拷贝的话,因为对于linkedlist中的所有引用类型采用new的方式生成新的对象并赋值,而不是简单的add(x.item)。
下面一个方法用于说明这以clone方法为浅拷贝。
class clone
{
public int a=2;
}
public static void main(String[] args)
{
LinkedList<clone> testClones=new LinkedList<clone>();
testClones.add(new clone());
testClones.add(new clone());
LinkedList<clone> cloneLinkedList=(LinkedList<com.songxu.action.clone>) testClones.clone();
testClones.get(0).a=4;
System.out.println(cloneLinkedList.get(0).a);
}
contains与indexof方法
contains,查看linkedlist中是否包含了指定了元素,它的实现是依靠indexof方法的返回值。
/**
* Returns <tt>true</tt> if this list contains the specified element.
* More formally, returns <tt>true</tt> if and only if this list contains
* at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this list is to be tested
* @return <tt>true</tt> if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
indexof方法很简单,根据元素是否为null,分别遍历,找到即返回。
toArray
将linkedlist转换为数组
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;
}
声明了一个对象数组,把linkedlist中的item依次放入数组中。
T[] toArray(T[] a)
将linkedlist复制到一个已知数组中,如果这个数组足够大,那么数组的前size个元素被linkedlist填充,size=null,后面保持不变。如果不够大,就尽心扩容,将linkedlist中元素返回。
public <T> T[] toArray(T[] a) {
if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
int i = 0;
Object[] result = a;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
if (a.length > size)
a[size] = null;
return a;
}
这个方法利用了反射方法,在数组容量不够的时候进行扩容。
迭代器 Iterator
内部类 iterator
私有内部类 ListItr实现了ListIterator 接口,
(1) 属性
private Node<E> lastReturned;
private Node<E> next;
private int nextIndex;
private int expectedModCount = modCount;
类中定义了四个私有变量
lastReturned 用于记录上一个返回的节点
next用于记录下一个要到达的节点
nextIndex 用于标志下一个索引
expectedModCount mod模操作,用于锁定Linkedlist操作,防止iterator操作期间,有其他线程对iterator进行操作。
(2) 构造器
ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
nextIndex = index;
}
构造器利用index索引进行初始化,来获得遍历的初始条件点
(3) 前后遍历方法
public boolean hasNext() {
return nextIndex < size;
}
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}
public boolean hasPrevious() {
return nextIndex > 0;
}
public E previous() {
checkForComodification();
if (!hasPrevious())
throw new NoSuchElementException();
lastReturned = next = (next == null) ? last : next.prev;
nextIndex--;
return lastReturned.item;
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex - 1;
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
在这些遍历的方法中,几乎都用到了checkForComodification这个方法,看方法的代码就知道了,就是在检查“操作模数”有没有改变过。mod的值只有在发生add、remove这一类的方法的时候发生改变。
(4) remove方法
public void remove() {
checkForComodification();
if (lastReturned == null)
throw new IllegalStateException();
Node<E> lastNext = lastReturned.next;
unlink(lastReturned);
if (next == lastReturned)
next = lastNext;
else
nextIndex--;
lastReturned = null;
expectedModCount++;
}
删除当前遍历指针(lastReturned)指向的节点,这一操作改变操作模数
(5)set方法
public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.item = e;
}
删除当前遍历指针(lastReturned)指向的节点的item值。这一操作没有改变操作模数,因为它不会影响整个链表的结构
(6)add方法
public void add(E e) {
checkForComodification();
lastReturned = null;
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}
在linkedlist尾部插入一个新的节点。
(7)forEachRemaining
java 1.8新加入的一个方法,使用lamada表达式对list进行遍历
public void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (modCount == expectedModCount && nextIndex < size) {
action.accept(next.item);
lastReturned = next;
next = next.next;
nextIndex++;
}
checkForComodification();
}
内部类 descendingIterator 升序迭代器
源自1.6版本,实现了Iterator接口
/**
* Adapter to provide descending iterators via ListItr.previous
*/
private class DescendingIterator implements Iterator<E> {
private final ListItr itr = new ListItr(size());
public boolean hasNext() {
return itr.hasPrevious();
}
public E next() {
return itr.previous();
}
public void remove() {
itr.remove();
}
}
这个类看名称以及它的注释就可以看出来,这是一个指针向前(previous)的适配器。
它的初始指针指向的尾节点,next()方法是向前遍历用的。
总结
1 LinkedList允许element值为空(null)
2 从1.5 1.6版本开始,LinkedList融合了栈和队列的同名方法