(一)List子父层级:
List接口继承于Collection,Collection继承Iterable; LIst接口实现类分为:Vector、ArrayList、LinkedList;
(二)List实现类
1、LinkedList实现类
《1)LinkedList底层是内部Node类的存储,prev、next、item值,同时最外层还有first、last节点;
(2)LinkedList是线程不安全的,多线程环境会报并发修改异常java.util.ConcurrentModificationException。
(3)LinkedList无扩容机制,底层是双向链表结构,内部是Node结构,外部是first、last首尾节点。
2、常见源码
(1)构造方法:
public LinkedList() { }
(2)add方法:
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++;
}
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;
}
}
(3)remove方法:
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;
}
E unlink(Node<E> x) {
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;
}
(4)get方法:
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
Node<E> node(int 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;
}
}
(5)set方法:
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
3、总结
(1)LinkedList是线程不安全,多线程环境会造成并发修改异常java.util.ConcurrentModificationException;
(2)LinkedList是一个双向链表结构(无扩容机制),内部是Node,外部是首尾节点first、last。
|