您的位置:首页 > 产品设计 > UI/UE

Java-Collection源码分析(五)——AbstractSequentiaList和LinkedList

2017-09-26 10:57 405 查看

一、AbstractSequentialList抽象类

这个类提供了一个基本的List接口实现,为实现序列访问的数据储存结构的提供了所需要的最小化的接口实现。对于支持随机访问数据的List比如数组,应该优先使用AbstractList。

是AbstractList类中与随机访问类相对的另一套系统,采用的是在迭代器的基础上实现的get、set、add和remove方法。

public abstract class AbstractSequentialList<E> extends AbstractList<E> {
protected AbstractSequentialList() {
}
public E get(int index) {
try {
return listIterator(index).next();
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("Index: "+index);
}
}
public E set(int index, E element) {
try {
ListIterator<E> e = listIterator(index);
E oldVal = e.next();
e.set(element);
return oldVal;
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("Index: "+index);
}
}
public void add(int index, E element) {
try {
listIterator(index).add(element);
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("Index: "+index);
}
}
public E remove(int index) {
try {
ListIterator<E> e = listIterator(index);
E outCast = e.next();
e.remove();
return outCast;
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("Index: "+index);
}
}

public boolean addAll(int index, Collection<? extends E> c) {
try {
boolean modified = false;
ListIterator<E> e1 = listIterator(index);
Iterator<? extends E> e2 = c.iterator();
while (e2.hasNext()) {
e1.add(e2.next());
modified = true;
}
return modified;
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("Index: "+index);
}
}
public Iterator<E> iterator() {
return listIterator();
}
public abstract ListIterator<E> listIterator(int index);
}
这个类的源码没什么好分析的,重点在LinkedList

二、LinkedList类

public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable{
transient int size = 0;
//指向第一个节点
transient Node<E> first;
//指向最后一个结点
transient Node<E> last;
//构造一个空列表
public LinkedList() {
}
//构造一个包含指定集合的元素的列表,按照集合的迭代器返回的顺序
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
//链接e作为第一个元素。
private void linkFirst(E e) {
final Node<E> f = first;
final Node<
4000
E> newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)//如果f为null,即e的nextnode 为空,e为lastnode
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}
//链接e作为最后最后一个元素
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++;
}
//在非空节点succ之前插入元素e
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++;
}

//取消链接非空第一个节点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;
}

//取消链接非空最后一个节点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;
}

//取消链接非空节点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;
}

//返回此列表中的第一个元素。
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}

//返回此列表中的最后一个元素。
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}

//从此列表中移除并返回第一个元素。
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}

//从此列表中删除并返回最后一个元素。
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}

//在此列表开头插入指定的元素。
public void addFirst(E e) {
linkFirst(e);
}

//将指定的元素追加到此列表的末尾
public void addLast(E e) {
linkLast(e);
}

//如果此列表包含指定的元素,则返回true。更多正式地,当且仅当此列表至少包含一个元素e时返回true,以便
public boolean contains(Object o) {
return indexOf(o) != -1;
}

//返回此列表中的元素数。
public int size() {
return size;
}

//将指定的元素追加到此列表的末尾。
public boolean add(E e) {
linkLast(e);
return true;
}
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 boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
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;
//设置pred、succ结点
if (index == size) {		//如果在列表后面添加,则将pred指向last
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}
//循环向列表中添加元素
for (Object o : a) {
E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null);
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;		//将pred指向新添加的结点
}
if (succ == null) {
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
size += numNew;
modCount++;
return true;
}

public void clear() {
//采用遍历的方式将列表中的元素设置为null
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++;
}
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
public void add(int index, E element) {
checkPositionIndex(index);

if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}

private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(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;
}
}
//根据元素查索引,采用了遍历查找
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++;
}
}
return -1;
}
//同indexOf方法,不过采用反向遍历的方式
public int lastIndexOf(Object o) {
int index = size;
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (x.item == null)
return index;
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (o.equals(x.item))
return index;
}
}
return -1;
}
//检索但不删除此列表的头(第一个元素)。如果为空则返回null
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
//检索但不删除此列表的头(第一个元素)。如果为空报NoSuchElementException错误
public E element() {
return getFirst();
}
//检索并删除此列表的头(第一个元素)。如果第一个元素为空则返回null
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
//检索并删除此列表的头(第一个元素)。如果第一个元素为空报NoSuchElementException错误
public E remove() {
return removeFirst();
}
//将指定的元素添加为此列表的尾部(最后一个元素)。
public boolean offer(E e) {
return add(e);
}
//在此列表的前面插入指定的元素。
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
//在该列表的末尾插入指定的元素。
public boolean offerLast(E e) {
addLast(e);
return true;
}
//检索但不删除此列表的第一个元素,如果此列表为空,则返回null
public E peekFirst() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
//检索但不删除此列表的最后一个元素,如果此列表为空,则返回null
public E peekLast() {
final Node<E> l = last;
return (l == null) ? null : l.item;
}
//检索并删除此列表的第一个元素,如果此列表为空,则返回null
public E pollFirst() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
//检索并删除此列表的最后一个元素,如果此列表为空,则返回null
public E pollLast() {
final Node<E> l = last;
return (l == null) ? null : unlinkLast(l);
}
//将元素推送到由此列表表示的堆栈上。 换句话说,在该列表的前面插入元素。
public void push(E e) {
addFirst(e);
}
//从此列表中的堆栈中弹出一个元素。 换句话说,删除并返回此列表的第一个元素。
public E pop() {
return removeFirst();
}
//删除此列表中指定元素的第一次出现(从头到尾遍历列表时)。 如果列表中不包含该元素,它将保持不变。
public boolean removeFirstOccurrence(Object o) {
return remove(o);
}
//删除此列表中指定元素的最后一次出现(从头到尾遍历列表时)。 如果列表中不包含该元素,它将保持不变。
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;
}

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;
}
}
}

在LinkedList中的add(),get(),remove(),set()等方法都是通过调用底层操作 linkFirst(),linkLast(),linkBefore(),unlinkFirst(),unlinkLast(),unlink()来实现的。在LinkedList 中还提供了队列和双端队列的方法,这些方法是通过调用add(),get(),remove(),set()等方法实现的。接下来着重通过图表的方式来解释。

linkFirst(E e) :



linkLast(E e):



linkBefore(E e, Node<E> succ)



unlinkFirst(Node<E> f)



unlinkLast(Node<E> l)



unlink(Node<E> x)
首先判断该节点是first节点还是last节点。如果是first节点,操作如unlinkFirst();如果是last节点,操作如同unlinkLast()。



三、LinkedList和ArrayList区别

ArrayList主要是通过数组的方式进行操作,能够在指定大小。在插入,删除等操作时需要对数组进行复制,消耗资源较多

LinkedList是通过建立节点进行操作,不可以指定大小,在查找,插入,删除等操作比较迅速。

ArrayList和LinkedList都是非同步的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: