publicbooleanremove(Object o){ // 如果要移除的结点为空则从头结点开始遍历直到找到值为空的结点将其链接释放 if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) { unlink(x); returntrue; } } } else { //否则找到一个值相等的结点 for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); returntrue; } } } returnfalse; }
// 遍历链表把每一个结点的属性都设置为null publicvoidclear(){ 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 E remove(int index){ // 判断索引位置是否合法 checkElementIndex(index); // 找到指定位置对应的结点将其释放其链接 return unlink(node(index)); }
toArray方法
创建一个数组,将链表所有结点的值都一一赋值到该数组上
1 2 3 4 5 6 7
public Object[] toArray() { Object[] result = new Object[size]; int i = 0; for (Node<E> x = first; x != null; x = x.next) result[i++] = x.item; return result; }