get方法
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
checkElementIndex
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
isElementIndex
transient int size = 0;
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
node
transient Node<E> first;
transient Node<E> last;
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;
}
}
peek方法
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
pop方法
移除首节点,如果首节点为null的话,会抛出异常
public E pop() {
return removeFirst();
}
removeFirst
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
unlinkFirst
private E unlinkFirst(Node<E> f) {
final E element = f.item;
final Node<E> next = f.next;
f.item = null;
f.next = null;
first = next;
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
poll方法
poll方法获取首节点,如果首节点不存在,则返回null
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
unlinkFirst
该方法可以参考pop方法中的unlinkFirst,已经记录就不在重新分析
remove方法
获取并移除首节点,如果不存在则抛出异常
public E remove() {
return removeFirst();
}
removeFirst
与pop方法一样,参考
add方法
add方法加在尾节点的后面
public boolean add(E e) {
linkLast(e);
return true;
}
linkLast
transient Node<E> last;
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++;
}
Node
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
set方法
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
checkElementIndex
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
node
参考前面get方法中的node
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;
}
}
push方法
push方法是加在第一个节点的前面
public void push(E e) {
addFirst(e);
}
addFirst
public void addFirst(E e) {
linkFirst(e);
}
linkFirst
transient Node<E> first;
transient Node<E> last;
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++;
}
offer方法
public boolean offer(E e) {
return add(e);
}
offer方法调用add方法,所以直接参考add方法即可
|