private static final long serialVersionUID = 876323262645176354L; //版本的序列号表示
transient int size = 0; //大小
transient Link<E> voidLink; //大小和头结点不参与序列化
上面是上下文的环境变量
具体数据的结点会有两个指针,指向前后两个结点
private static final class Link<ET> {
ET data;
Link<ET> previous, next;
Link(ET o, Link<ET> p, Link<ET> n) {
data = o;
previous = p;
next = n;
}
}
/**
* Constructs a new empty instance of {@code LinkedList}.
*/
public LinkedList() {
voidLink = new Link<E>(null, null, null);
voidLink.previous = voidLink;
voidLink.next = voidLink;
}
创建头检点,并将数据的两个指针串接起来,后面还定义了针对Collection的结构体初始化
增加结点:
创新的地方对location进行定位,而不仅仅是直接从头开始遍历
@Override
public void add(int location, E object) {
if (location >= 0 && location <= size) {
Link<E> link = voidLink;
if (location < (size / 2)) {
for (int i = 0; i <= location; i++) {
link = link.next;
}
} else {
for (int i = size; i > location; i--) {
link = link.previous;
}
}
Link<E> previous = link.previous;
Link<E> newLink = new Link<E>(object, previous, link);
previous.next = newLink;
link.previous = newLink;
size++;
modCount++;
} else {
throw new IndexOutOfBoundsException();
}
}
高效的定位:(自己可能会从头开始扫描,效率是需要思考的内容)
if (location < (size / 2)) {
for (int i = 0; i <= location; i++) {
link = link.next;
}
} else {
for (int i = size; i > location; i--) {
link = link.previous;
}
}
专门写了一个加入最后一个结点的函数,竟然没有复用position的代码
public boolean add(E object) {
return addLastImpl(object);
}
@Override
public boolean addAll(int location, Collection<? extends E> collection) {
if (location < 0 || location > size) {
throw new IndexOutOfBoundsException();
}
int adding = collection.size();
if (adding == 0) {
return false;
}
Collection<? extends E> elements = (collection == this) ?
new ArrayList<E>(collection) : collection;
Link<E> previous = voidLink;
if (location < (size / 2)) {
for (int i = 0; i < location; i++) {
previous = previous.next;
}
} else {
for (int i = size; i >= location; i--) {
previous = previous.previous;
}
}
Link<E> next = previous.next;
for (E e : elements) {
Link<E> newLink = new Link<E>(e, previous, null);
previous.next = newLink;
previous = newLink;
}
previous.next = next;
next.previous = previous;
size += adding;
modCount++;
return true;
}
清零,直接清掉,竟然没有专门去释放指针为空,java会自动回收
public void clear() { if (size > 0) { size = 0; voidLink.next = voidLink; voidLink.previous = voidLink; modCount++; } }
toArray有个特殊的操作自己没怎么用过public <T> T[] toArray(T[] contents) { int index = 0; if (size > contents.length) { Class<?> ct = contents.getClass().(); contents = (T[]) Array.newInstance(ct, size); //这个可以创建一个类列表,而类的类型从getComponentType() } Link<E> link = voidLink.next; while (link != voidLink) { contents[index++] = (T) link.data; link = link.next; } if (index < contents.length) { contents[index] = null; } return contents; }