ArrayList和linkedlist的add方法


ArrayList和linkedlist的add方法

  • ArrayList和linkedlist都繼承Collection和List接口.

Arraylist

  • transient Object[] elementData; // non-private to simplify nested class access(非私有以簡化嵌套類訪問)
public boolean add(E e) {
        ensureCapacityInternal(size + 1);  
        elementData[size++] = e;
        return true;
    }

add方法,總是返回true。
用數組elementData來保存,在此數組中保存至最后。

  • 圖解 add
    enter description here
    就是ArrayList里面的elementData數組里面最后一個元素后面進行添加一個。

LinkList

public boolean add(E e) {
        linkLast(e);
        return true;
    }

也總是返回true。在linkLast中實現的是鏈表
List內部實現的雙鏈表,lsat是最末位的元素,linkLast把元素連接到末位。

/** * Links e as last element.鏈接e作為最后一個元素。 */
    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++;
    }
  • 圖解
    源碼用的是尾插法:
    插入前:
    enter description here
    插入后:
    enter description here
    這是Node表(類)
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;
        }
    }

源碼尾插法解釋:

  • 尾插法,就是在鏈表最末位添加表。
  • final Node l = last; 創建l 等於 鏈表中最后一個表last指向的位置。
  • final Node newNode = new Node<>(l, e, null); 創建新的表,上一個指向l,元素為e,因為是末位,所以下個是空
  • last = newNode; 此時last應該是新建的newNode了
  • if (l == null) 判斷是不是空鏈表,
    first = newNode; 空鏈表,表頭first也指向newNode
    else
  • l.next = newNode; l是開始保存last的位置,l.next與newNode鏈接起來,此時,鏈表是一個完整的鏈表。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM