> 技术文档 > Java(LinkedList和ArrayList底层分析)_java linkedlist.remove

Java(LinkedList和ArrayList底层分析)_java linkedlist.remove


LinkedList全面说明:

LinkedList底层操作机制:

LinkedList的方法:

add():增加节点对象

remove():删除一个节点对象(默认删除第一个节点对象)

set():修改一个节点对象

get():得到一个节点对象

LinkedList的遍历:

增强for循环

迭代器

普通for循化

LinkedList的源码解读:

增加源码:

1. LinkedList linkedList = new LinkedList();
       public LinkedList() {}
2. 这时 linkeList 的属性 first = null last = null

3. 执行 添加
public boolean add(E e) {
       linkLast(e);
       return true;
}
4.将新的结点,加入到双向链表的最后
void linkLast(E e) {
         final Node l = last;
         final Node newNode = new Node(l, e, null);
         last = newNode;
     if (l == null)
         first = newNode;
    else
        l.next = newNode;
   size++;
   modCount++;
}

删除源码:

1. 执行 removeFirst
public E remove() {
       return removeFirst();
}

2. 执行
public E removeFirst() {
     final Node f = first;
        if (f == null)
        throw new NoSuchElementException();
    return unlinkFirst(f);
}

3. 执行 unlinkFirst, 将 f 指向的双向链表的第一个结点拿掉
private E unlinkFirst(Node f) {
         final E element = f.item;
         final Node 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;
}

ArrayList 和 LinkedList 比较: