LinkedList是一个用链表实现的集合,元素有序且可以重复。
和ArrayList集合一样,LinkedList集合也实现了Cloneable接口和Serializable接口
注意:相对于ArrayList集合,LinkedList集合多实现了一个Deque接口,这是一个双向队列接口,双向队列接口就是两端都可以进行增加和删除操作。
// 链表元素(节点)的个数
transient int size = 0;
/**
* Pointer to first node.指向第一个节点的指针
*/
transient Node<E> first;
/**
* Pointer to last node.指向最后一个节点的指针
*/
transient Node<E> last;
注意这里出现了一个Node类,这是LinkedList类中的内部类,其中每一个元素就代表一个Node类对象,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;
}
}
/**
* 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);
}
LinkedList有两个构造函数,第一个是默认的空的构造函数,第二个是将已有元素的集合Collection的实例添加到LinkedList中,调用的是addAll()方法,这个方法下面介绍。
注意:LinkedList是没有初始化链表大小的构造函数,因为链表不像数组,一个定义好的数组是必须要有确定的大小,然后去分配内存空间,而链表不一样,它没有确定的大小,通过指针的移动来指向下一个内存地址的分配。
①、void addFirst(E e) 将指定元素添加到链表头
/**
* Inserts the specified element at the beginning of this list.
* 将指定的元素附加到链表头节点
* @param e the element to add
*/
public void addFirst(E e) {
linkFirst(e);
}
/**
* Links e as first element.
*/
private void linkFirst(E e) {
//将头节点赋值给 f
final Node<E> f = first;
//将指定元素构造成一个新节点,此节点的指向下一个节点的引用为头节点
final Node<E> newNode = new Node<>(null, e, f);
//将新节点设为头节点,那么原先的头节点 f 变为第二个节点
first = newNode;
//如果第二个节点为空,也就是原先链表为空
if (f == null)
//将这个新节点也设为尾节点,前面已经设为头节点了
last = newNode;
else
//将原先的头节点的上一个节点指向新节点
f.prev = newNode;
//节点数加1
size++;
//和ArrayList中一样,iterator和listIterator方法返回的迭代器和列表迭代器实现使用
modCount++;
}
②、public void addLast(E e) 和 public boolean add(E e) 将指定元素添加到链表尾
// 将元素添加到链表末尾
public boolean add(E e) {
linkLast(e);
return true;
}
// 将元素添加到链表末尾
public void addLast(E e) {
linkLast(e);
}
// 被其他方法调用的真正实现链表末尾添加算法
void linkLast(E e) {
// 将l设为尾节点
final Node<E> l = last;
// 构造一个新节点,节点上一个节点引用指向尾节点l
final Node<E> newNode = new Node<>(l, e, null);
// 将尾节点设为创建的新节点
last = newNode;
// 如果尾节点为空,表示原先链表为空
if (l == null)
// 将头节点设为新创建的节点(尾节点也是新创建的节点)
first = newNode;
else
// 将原来尾节点下一个节点的引用指向新节点
l.next = newNode;
// 节点数加1
size++;
// 和ArrayList中一样,iterator和listIterator方法返回的迭代器和列表迭代器实现使用
modCount++;
}
③、public void add(int index, E element) 将指定的元素插入此列表中的指定位置
/**
* 将指定的元素插入此列表中的指定位置
*/
public void add(int index, E element) {
// 判断索引 index >=0 && index <=size中时抛出IndexOutOfBoundsException异常
checkPositionIndex(index);
// 如果索引值等于链表大小
if (index == size)
//将节点插入到尾节点
linkLast(element);
else
//
linkBefore(element, node(index));
}
// 被其他方法调用的真正实现链表末尾添加算法
void linkLast(E e) {
// 将l设为尾节点
final Node<E> l = last;
// 构造一个新节点,节点上一个节点引用指向尾节点l
final Node<E> newNode = new Node<>(l, e, null);
// 将尾节点设为创建的新节点
last = newNode;
// 如果尾节点为空,表示原先链表为空
if (l == null)
// 将头节点设为新创建的节点(尾节点也是新创建的节点)
first = newNode;
else
// 将原来尾节点下一个节点的引用指向新节点
l.next = newNode;
// 节点数加1
size++;
// 和ArrayList中一样,iterator和listIterator方法返回的迭代器和列表迭代器实现使用
modCount++;
}
/**
* Inserts element e before non-null Node succ.
*/
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
// 将pred设为插入节点的上一个节点
final Node<E> pred = succ.prev;
// 将新节点的上引用设为pred,下引用设为succ
final Node<E> newNode = new Node<>(pred, e, succ);
// succ的上一个节点的引用设为新节点
succ.prev = newNode;
// 如果插入节点的上一个节点引用为空
if (pred == null)
// 新节点就是头节点
first = newNode;
else
// 插入节点的下一个节点引用设为新节点
pred.next = newNode;
size++;
modCount++;
}
④、public boolean addAll(Collection extends E> c) 按照指定集合的迭代器返回的顺序,将指定集合的所有元素追加到此列表的末尾
此方法还有一个 public boolean addAll(int index, Collection extends E> c) ,将集合c中所有元素插入到指定索引的位置。
理所当然:addAll(Collection extends E> c) == addAll(size, Collection extends E> c)
// 按照指定集合的迭代器返回的顺序,将指定集合中的所有元素追加到此列表的末尾
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
// 将集合 c 中所有元素插入到指定索引的位置
public boolean addAll(int index, Collection<? extends E> c) {
// 判断索引 index >=0 && index <=size中时抛出IndexOutOfBoundsException异常
checkPositionIndex(index);
// 将集合转换成一个Object类型的数组
Object[] a = c.toArray();
int numNew = a.length;
// 如果添加的集合为空,直接返回false
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;
}
看到上面想LinkedList集合中添加元素的各种方式,我们发现LinkedList每次添加元素只是改变元素的上一个指针引用和下一个指针引用,而且没有扩容。对比于ArrayList,需要扩容,而且在中间插入元素时,后面的所有元素都要移动一位,两者插入元素时的效率差异很大,下一篇博客会对这两者的效率,以及何种情况选择何种集合进行分析。
删除元素和添加元素一样,也是通过更改指向上一个节点和指向下一个节点的引用即可。
①、 public E remove() 和 public E removeFirst() 从此列表中移除并返回第一个元素
// 从此列表中移除并返回第一个元素
public E remove() {
return removeFirst();
}
// 从此列表中移除并返回第一个元素
public E removeFirst() {
// f设为头节点
final Node<E> 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;
// next 为头结点的下一个节点
final Node<E> next = f.next;
f.item = null;
// 将节点的元素以及引用都设为 null,便于垃圾回收
f.next = null; // help GC
// 修改头结点为第二个节点
first = next;
// 如果第二个节点为空(当前链表只存在第一个元素)
if (next == null)
// 那么尾节点也设置为 null
last = null;
else
// 如果第二个节点不为空, 那么将第二个节点的上一个引用置为 null
next.prev = null;
size--;
modCount++;
return element;
}
② public E removeLast() 从该列表中删除并返回最后一个元素
// 从该列表中删除并返回最后一个元素
public E removeLast() {
final Node<E> l = last;
if (l == null)
// 如果尾节点为空,表示当前集合为空,则抛出异常
throw new NoSuchElementException();
return unlinkLast(l);
}
/**
* 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;
// 将节点的元素以及引用都设为null, 便于垃圾回收
l.prev = null; // help GC
// 尾节点为倒数第二个节点
last = prev;
// 如果倒数第二个节点为null
if (prev == null)
// 那么将节点也置为null
first = null;
else
// 如果单数第二个节点不为空,那么将倒数第二个节点的下一个引用置为 null
prev.next = null;
size--;
modCount++;
return element;
}
③ public E remove(int index) 删除此列表中指定位置的元素
// 删除此列表中指定位置的元素
public E remove(int index) {
// 判断索引 index >=0 && index <=size中时有问题抛出IndexOutOfBoundsException异常
checkElementIndex(index);
return unlink(node(index));
}
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;
// 如果删除节点位置的上一个节点引用为null(表示删除第一个元素)
if (prev == null) {
// 将头结点置为第一个元素的下一个节点
first = next;
// 如果删除节点位置的上一个引用不为null
} else {
// 将删除节点的上一个节点的下一个节点引用指向删除节点的下一个节点(去掉删除节点)
prev.next = next;
// 删除节点的上一个节点引用置为null
x.prev = null;
}
// 如果删除节点的下一个节点引用为null(表示删除最后一个节点)
if (next == null) {
// 将尾节点置为删除节点的上一个节点
last = prev;
// 不是删除尾节点
} else {
// 将删除节点的下一个节点的上一个节点的引用指向删除节点的上一个节点
next.prev = prev;
// 将删除节点的下一个节点引用置为null
x.next = null;
}
// 删除节点内容置为null,便于垃圾回收
x.item = null;
size--;
modCount++;
return element;
}
④、public boolean remove(Object o) 如果存在,则从该列表中删除指定元素的第一次出现
此方法本质上和 remove(int index)没多大区别,通过循环判断元素进行删除,需要注意的是,是删除第一次出现的元素,不是所有的
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;
}
通过调用 public E set(int index, E element) 方法, 用指定的元素替换此列表中指定位置的元素
public E set(int index, E element) {
checkElementIndex(index);
// 获取指定索引处的元素
Node<E> x = node(index);
E oldVal = x.item;
// 将指定位置的元素替换成要修改的元素
x.item = element;
// 返回指定索引位置原来的元素
return oldVal;
}
这里主要是通过 node(index) 方法获取指定索引位置的节点,然后修改此节点位置的元素即可。
①、public E 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<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
②、public E 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<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
③、public E 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;
}
④、public int indexOf(Object o) 返回此列表中指定元素第一次出现的索引,如果此列表不包含元素,则返回-1
// 返回此列表中指定元素第一次出现的索引,如果此列表不包含元素,则返回-1
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
// 找不到返回 -1
return -1;
}
使用迭代器
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("A");
linkedList.add("B");
linkedList.add("C");
linkedList.add("D");
Iterator<String> listIt = linkedList.listIterator();
while(listIt.hasNext()){
System.out.print(listIt.next()+" ");//A B C D
}
//通过适配器模式实现的接口,作用是倒叙打印链表
Iterator<String> it = linkedList.descendingIterator();
while(it.hasNext()){
System.out.print(it.next()+" ");//D C B A
}
在 LinkedList 集合中也有一个内部类 ListItr,方法实现大体上也差不多,通过移动游标指向每一次要遍历的元素,**不用在遍历某个元素之前都要从头开始。**其方法实现也比较简单:
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
private class ListItr implements ListIterator<E> {
private Node<E> lastReturned;
private Node<E> next;
private int nextIndex;
private int expectedModCount = modCount;
ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
nextIndex = index;
}
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;
}
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++;
}
public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.item = e;
}
public void add(E e) {
checkForComodification();
lastReturned = null;
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}
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();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
这里需要重点注意的是modCount字段,前面我们在增加和删除元素的时候,都会进行自增操作modCount,这是因为如果想一边迭代,一边用集合自带的方法进行删除或者新增操作,都会抛出异常。(使用迭代器的增删方法不会抛异常)
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
迭代器的另一种形式就是使用foreach循环,底层实现也是使用的迭代器,语法糖
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("A");
linkedList.add("B");
linkedList.add("C");
linkedList.add("D");
for(String str : linkedList){
System.out.print(str + "");
}
import java.util.Iterator;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<Integer> linkedList = new LinkedList<>();
for(int i = 0; i < 100000 ; i++) {
linkedList.add(i);
}
long beginTimeFor = System.currentTimeMillis();
for(int i = 0; i < 100000; i++) {
// 这里每次get都会去循环从头一遍找
linkedList.get(i);
}
long endTimeFor = System.currentTimeMillis();
System.out.println("使用普通for循环遍历10000个元素需要的时间:" + (endTimeFor - beginTimeFor));
long beginTimeIte = System.currentTimeMillis();
Iterator<Integer> it = linkedList.listIterator();
while(it.hasNext()) {
it.next();
}
long endTimeIte = System.currentTimeMillis();
System.out.println("使用迭代器遍历10000个元素需要的时间:" + (endTimeIte - beginTimeIte));
}
}
运行结果:
使用普通for循环遍历10000个元素需要的时间:7271
使用迭代器遍历10000个元素需要的时间:4
普通for循环:每次遍历一个索引的元素之前,都要访问之前所有的索引。
迭代器:每次访问一个元素后。都会用游标记录当前访问元素的位置,遍历一个元素,记录一个位置。
参考博客:https://www.cnblogs.com/ysocean/p/8657850.html#_label3_0