首頁  >  文章  >  Java  >  分享ArrayList中的幾個常用方法的源碼

分享ArrayList中的幾個常用方法的源碼

零下一度
零下一度原創
2017-06-28 09:41:471761瀏覽

jdk1.7.0_79 

  上文裡解析了有關ArrayList中的幾個常用方法的原始碼-《有關ArrayList常用方法的原始碼解析》,本文將對LinkedList的常用方法做簡要解析

  LinkedList是基於鍊錶實作的,也就是說它具備了鍊錶的優點和缺點,隨機存取慢、插入刪除速度快。既然是鍊錶,那麼它就存在節點資料結構,也不存在容量大小的問題,來一個在尾部添加一個。

//LinkedList$Nodeprivate 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;
    }
}

  第一個預設不帶參數的建構方法,建構一個空鍊錶。

//1.LinkedList,默认构造方法public LinkedList() {
}

  第二個建構方法能把一個集合當作一個參數傳遞,同時集合中的元素需要是LinkedList的子類別

//2.LinkedList,能将一个集合作为参数的构造方法public LinkedList(Collection<? extends E> c) {this();
    addAll(c);
}

  兩個建構方法都比較簡單,接下來看元素的插入及刪除等方法。

public boolean add(E e) {
    linkLast(e);    //将元素添加到链表尾部return true;
}
//LinkedList#linkLastvoid linkLast(E e) {final Node<E> l = last;    //链表尾指针引用暂存final Node<E> newNode = new Node<>(l, e, null);    //构造新节点last = newNode;    //将链表的尾指针指向新节点if (l == null)    //此时为第一次插入元素first = newNode;elsel.next = newNode;    
    size++;    //链表数据总数+1modCount++;    //modCount变量在《有关ArrayList常用方法的源码解析》提到过,增删都会+1,防止一个线程在用迭代器遍历的时候,另一个线程在对其进行修改。}

  學過《資料結構》的同學相信看到鍊錶的操作不會感到陌生,接著來看看刪除指定位置的元素remove(int)方法。

 

//LinkedList#removepublic E remove(int index) {
    checkElementIndex(index);    //检查是否越界 index >= 0 && index <= sizereturn unlink(node(index));    //调用node方法查找并返回指定索引位置的Node节点}

 

#
//LinkedList#node,根据索引位置返回Node节点Node<E> node(int index) {if (index < (size >> 1)) {    //size >> 1 = size / 2,如果索引位于链表前半部分,则移动fisrt头指针进行查找Node<E> x = first;for (int i = 0; i < index; i++)
            x = x.next;return x;
    } else {    //如果索引位于链表后半部分,则移动last尾指针进行查找Node<E> x = last;for (int i = size - 1; i > index; i--)
            x = x.prev;return x;
    }
}

  查找到index#位置的Node,呼叫unlink方法摘掉該節點

//LinkedList#unlink,一看即懂E unlink(Node<E> x) {// assert x != null;final E element = x.item;final Node<E> next = x.next;final Node<E> prev = x.prev;if (prev == null) {
        first = next;
    } else {
        prev.next = next;
        x.prev = null;
    }if (next == null) {
        last = prev;
    } else {
        next.prev = prev;
        x.next = null;
    }

    x.item = null;
    size--;
    modCount++;return element;
}

  從程式碼中就能看出LinkedListArrayList兩者的優缺點,由於只涉及簡單的鍊錶資料結構,所以不再對其他方法進行解析。

 

以上是分享ArrayList中的幾個常用方法的源碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn