成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

LinkedList 基本示例及源碼解析

senntyou / 3074人閱讀

摘要:對(duì)于不可修改的列表來(lái)說(shuō),程序員需要實(shí)現(xiàn)列表迭代器的和方法介紹這個(gè)接口也是繼承類層次的核心接口,以求最大限度的減少實(shí)現(xiàn)此接口的工作量,由順序訪問(wèn)數(shù)據(jù)存儲(chǔ)例如鏈接鏈表支持。

一、JavaDoc 簡(jiǎn)介

LinkedList雙向鏈表,實(shí)現(xiàn)了List的 雙向隊(duì)列接口,實(shí)現(xiàn)了所有l(wèi)ist可選擇性操作,允許存儲(chǔ)任何元素(包括null值)

所有的操作都可以表現(xiàn)為雙向性的,遍歷的時(shí)候會(huì)從首部到尾部進(jìn)行遍歷,直到找到最近的元素位置

注意這個(gè)實(shí)現(xiàn)不是線程安全的, 如果多個(gè)線程并發(fā)訪問(wèn)鏈表,并且至少其中的一個(gè)線程修改了鏈表的結(jié)構(gòu),那么這個(gè)鏈表必須進(jìn)行外部加鎖。(結(jié)構(gòu)化的操作指的是任何添加或者刪除至少一個(gè)元素的操作,僅僅對(duì)已有元素的值進(jìn)行修改不是結(jié)構(gòu)化的操作)。

List list = Collections.synchronizedList(new LinkedList(…)), 可以用這種鏈表做同步訪問(wèn),但是最好在創(chuàng)建的時(shí)間就這樣做,避免意外的非同步對(duì)鏈表的訪問(wèn)

迭代器返回的iterators 和 listIterator方法會(huì)造成fail-fast機(jī)制:如果鏈表在生成迭代器之后被結(jié)構(gòu)化的修改了,除了使用iterator獨(dú)有的remove方法外,都會(huì)拋出并發(fā)修改的異常因此,在面對(duì)并發(fā)修改的時(shí)候,這個(gè)迭代器能夠快速失敗,從而避免非確定性的問(wèn)題

二、LinkedList 繼承接口和實(shí)現(xiàn)類介紹

java.util.LinkedList 繼承了 AbstractSequentialList 并實(shí)現(xiàn)了List , Deque , Cloneable 接口,以及Serializable 接口

public class LinkedList
    extends AbstractSequentialList
    implements List, Deque, Cloneable, java.io.Serializable {}

類之間的繼承體系如下:

下面就對(duì)繼承樹(shù)中的部分節(jié)點(diǎn)進(jìn)行大致介紹:

AbstractSequentialList 介紹:
這個(gè)接口是List一系列子類接口的核心接口,以求最大限度的減少實(shí)現(xiàn)此接口的工作量,由順序訪問(wèn)數(shù)據(jù)存儲(chǔ)(例如鏈接鏈表)支持。對(duì)于隨機(jī)訪問(wèn)的數(shù)據(jù)(像是數(shù)組),AbstractList 應(yīng)該優(yōu)先被使用這個(gè)接口可以說(shuō)是與AbstractList類相反的,它實(shí)現(xiàn)了隨機(jī)訪問(wèn)方法,提供了get(int index),set(int index,E element), add(int index,E element) and remove(int index)方法

對(duì)于程序員來(lái)說(shuō):

要實(shí)現(xiàn)一個(gè)列表,程序員只需要擴(kuò)展這個(gè)類并且提供listIterator 和 size方法即可。
對(duì)于不可修改的列表來(lái)說(shuō), 程序員需要實(shí)現(xiàn)列表迭代器的 hasNext(), next(), hasPrevious(),
previous 和 index 方法

AbstractList 介紹:

這個(gè)接口也是List繼承類層次的核心接口,以求最大限度的減少實(shí)現(xiàn)此接口的工作量,由順序訪問(wèn)
數(shù)據(jù)存儲(chǔ)(例如鏈接鏈表)支持。對(duì)于順序訪問(wèn)的數(shù)據(jù)(像是鏈表),AbstractSequentialList 應(yīng)該優(yōu)先被使用,
如果需要實(shí)現(xiàn)不可修改的list,程序員需要擴(kuò)展這個(gè)類,list需要實(shí)現(xiàn)get(int) 方法和List.size()方法
如果需要實(shí)現(xiàn)可修改的list,程序員必須額外重寫(xiě)set(int,Object) set(int,E)方法(否則會(huì)拋出
UnsupportedOperationException的異常),如果list是可變大小的,程序員必須額外重寫(xiě)add(int,Object) , add(int, E) and remove(int) 方法

AbstractCollection 介紹:

這個(gè)接口是Collection接口的一個(gè)核心實(shí)現(xiàn),盡量減少實(shí)現(xiàn)此接口所需的工作量
為了實(shí)現(xiàn)不可修改的collection,程序員應(yīng)該繼承這個(gè)類并提供呢iterator和size 方法
為了實(shí)現(xiàn)可修改的collection,程序團(tuán)需要額外重寫(xiě)類的add方法,iterator方法返回的Iterator迭代器也必須實(shí)現(xiàn)remove方法

三、LinkedList 基本方法介紹

上面看完了LinkedList 的繼承體系之后,來(lái)看看LinkedList的基本方法說(shuō)明

字比較小,可能有些不清晰,下面我就來(lái)對(duì)上面圖片做一個(gè)大致介紹:

添加
    add():
    ----> 1. add(E e) :  直接在"末尾"處添加元素
  ----> 2. add(int index,E element) : 在"指定索引處添"加元素
  ----> 3. addAll(Collections c) : 在"末尾"處添加一個(gè)collection集合
  ----> 4. addAll(int index,Collections c):在"指定位置"添加一個(gè)collection集合
  ----> 5. addFirst(E e): 在"頭部"添加指定元素
  ----> 6. addLast(E e): 在"尾部"添加指定元素
  
  offer():
  ----> 1. offer(E e): 在鏈表"末尾"添加元素
  ----> 2. offerFirst(E e): 在"鏈表頭"添加指定元素
  ----> 3. offerLast(E e): 在"鏈表尾"添加指定元素
  
  push(E e): 在"頭部"壓入元素
  
移除
  
  poll():
  ----> 1. poll(): 訪問(wèn)并移除"首部"元素
  ----> 2. pollFirst(): 訪問(wèn)并移除"首部"元素
  ----> 3. pollLast(): 訪問(wèn)并移除"尾部"元素
  
  pop(): 從列表代表的堆棧中彈出元素,從"頭部"彈出
  
  remove(): 
  ----> 1. remove(): 移除并返回"首部"元素
  ----> 2. remove(int index) : 移除"指定索引"處的元素
  ----> 3. remove(Object o): 移除指定元素
  ----> 4. removeFirst(): 移除并返回"第一個(gè)"元素
  ----> 5. removeFirstOccurrence(Object o): 從頭到尾遍歷,移除"第一次"出現(xiàn)的元素
  ----> 6. removeLast(): 移除并返回"最后一個(gè)"元素
  ----> 7. removeLastOccurrence(Object o): 從頭到尾遍歷,移除"最后一次"出現(xiàn)的元素
  
  clear(): 清空所有元素
  
訪問(wèn)

    peek(): 
  ----> 1. peek(): 只訪問(wèn),不移除"首部"元素
  ----> 2. peekFirst(): 只訪問(wèn),不移除"首部"元素,如果鏈表不包含任何元素,則返回null
  ----> 3. peekLast(): 只訪問(wèn),不移除"尾部"元素,如果鏈表不包含任何元素,返回null
  
  element(): 只訪問(wèn),不移除"頭部"元素
    
  get():
  ----> 1. get(int index): 返回"指定索引"處的元素
  ----> 2. getFirst(): 返回"第一個(gè)"元素
  ----> 3. getLast(): 返回"最后一個(gè)"元素

  indexOf(Object o): 檢索某個(gè)元素"第一次"出現(xiàn)所在的位置
  LastIndexOf(Object o): 檢索某個(gè)元素"最后一次"出現(xiàn)的位置
  
 其他
 
     clone() : 返回一個(gè)鏈表的拷貝,返回值為Object 類型
      contains(Object o): 判斷鏈表是否包含某個(gè)元素
      descendingIterator(): 返回一個(gè)迭代器,里面的元素是倒敘返回的
      listIterator(int index) : 在指定索引處創(chuàng)建一個(gè)"雙向遍歷迭代器"
    set(int index, E element): 替換某個(gè)位置處的元素
      size() : 返回鏈表的長(zhǎng)度
      spliterator(): 創(chuàng)建一個(gè)后期綁定并快速失敗的元素
      toArray(): 將鏈表轉(zhuǎn)變?yōu)閿?shù)組返回
  
四、LinkedList 基本方法使用

學(xué)以致用,熟悉了上面基本方法之后,來(lái)簡(jiǎn)單做一個(gè)demo測(cè)試一下上面的方法:

/** 
 * 此方法描述
 * LinedList 集合的基本使用
 */
public class LinkedListTest {

    public static void main(String[] args) {

        LinkedList list = new LinkedList<>();
        list.add("111");
        list.add("222");
        list.add("333");
        list.add(1,"123");

        // 分別在頭部和尾部添加元素
        list.addFirst("top");
        list.addLast("bottom");
        System.out.println(list);

        // 數(shù)組克隆
        Object listClone = list.clone();
        System.out.println(listClone);

        // 創(chuàng)建一個(gè)首尾互換的迭代器
        Iterator it = list.descendingIterator();
        while (it.hasNext()){
            System.out.print(it.next() + " ");
        }
        System.out.println();
        list.clear();
        System.out.println("list.contains("111") ? " + list.contains("111"));

        Collection collec = Arrays.asList("123","213","321");
        list.addAll(collec);
        System.out.println(list);
        System.out.println("list.element = " + list.element());
        System.out.println("list.get(2) = " + list.get(2));
        System.out.println("list.getFirst() = " + list.getFirst());
        System.out.println("list.getLast() = " + list.getLast());

        // 檢索指定元素出現(xiàn)的位置
        System.out.println("list.indexOf(213) = " + list.indexOf("213"));
        list.add("123");
        System.out.println("list.lastIndexOf(123) = " + list.lastIndexOf("123"));
        // 在首部和尾部添加元素
        list.offerFirst("first");
        list.offerLast("999");
        System.out.println("list = " + list);
        list.offer("last");
        // 只訪問(wèn),不移除指定元素
        System.out.println("list.peek() = " + list.peek());
        System.out.println("list.peekFirst() = " + list.peekFirst());
        System.out.println("list.peekLast() = " + list.peekLast());

        // 訪問(wèn)并移除元素
        System.out.println("list.poll() = " + list.poll());
        System.out.println("list.pollFirst() = " + list.pollFirst());
        System.out.println("list.pollLast() = " + list.pollLast());
        System.out.println("list = " + list);
        // 從首部彈出元素
        list.pop();
        // 壓入元素
        list.push("123");
        System.out.println("list.size() = " + list.size());
        System.out.println("list = " + list);

        // remove操作
        System.out.println(list.remove());
        System.out.println(list.remove(1));
        System.out.println(list.remove("999"));
        System.out.println(list.removeFirst());
        System.out.println("list = " + list);

        list.addAll(collec);
        list.addFirst("123");
        list.addLast("123");
        System.out.println("list = " + list);
        list.removeFirstOccurrence("123");
        list.removeLastOccurrence("123");
        list.removeLast();
        System.out.println("list = " + list);
        list.addFirst("top");
        list.addLast("bottom");
        list.set(2,"321");
        System.out.println("list = " + list);
        System.out.println("--------------------------");

        // 創(chuàng)建一個(gè)list的雙向鏈表
        ListIterator listIterator = list.listIterator();
        while(listIterator.hasNext()){
            // 移到list的末端
            System.out.println(listIterator.next());
        }
        System.out.println("--------------------------");
        while (listIterator.hasPrevious()){
            // 移到list的首端
            System.out.println(listIterator.previous());
        }    
    }
}

Console:

-------1------- [top, 111, 123, 222, 333, bottom]
-------2-------[top, 111, 123, 222, 333, bottom]
bottom 333 222 123 111 top 
list.contains("111") ? false
[123, 213, 321]
list.element = 123
list.get(2) = 321
list.getFirst() = 123
list.getLast() = 321
list.indexOf(213) = 1
list.lastIndexOf(123) = 3
-------4------- [first, 123, 213, 321, 123, 999]
list.peek() = first
list.peekFirst() = first
list.peekLast() = last
list.poll() = first
list.pollFirst() = 123
list.pollLast() = last
-------5------- [213, 321, 123, 999]
list.size() = 4
-------6------- [123, 321, 123, 999]
123
123
true
321
-------7------- []
-------8------- [123, 123, 213, 321, 123]
list = [123, 213]
-------9------- [top, 123, 321, bottom]
--------------------------
top
123
321
bottom
--------------------------
bottom
321
123
top
五、LinkedList 內(nèi)部結(jié)構(gòu)以及基本元素聲明

LinkedList內(nèi)部結(jié)構(gòu)是一個(gè)雙向鏈表具體示意圖如下

每一個(gè)鏈表都是一個(gè)Node節(jié)點(diǎn),由三個(gè)元素組成

private static class Node {
          // Node節(jié)點(diǎn)的元素
        E item;
          // 指向下一個(gè)元素
        Node next;
          // 指向上一個(gè)元素
        Node prev;

          // 節(jié)點(diǎn)構(gòu)造函數(shù)
        Node(Node prev, E element, Node next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
}

first 節(jié)點(diǎn)也是頭節(jié)點(diǎn), last節(jié)點(diǎn)也是尾節(jié)點(diǎn)

LinkedList 中有三個(gè)元素,分別是

transient int size = 0; // 鏈表的容量

transient Node first; // 指向第一個(gè)節(jié)點(diǎn)

transient Node last; // 指向最后一個(gè)節(jié)點(diǎn)

LinkedList 有兩個(gè)構(gòu)造函數(shù),一個(gè)是空構(gòu)造函數(shù),不添加任何元素,一種是創(chuàng)建的時(shí)候就接收一個(gè)Collection集合。

    /**
     * 空構(gòu)造函數(shù)
     */
    public LinkedList() {}

    /**
     * 創(chuàng)建一個(gè)包含指定元素的構(gòu)造函數(shù)
     */
    public LinkedList(Collection c) {
      this();
      addAll(c);
    }
六、LinkedList 具體源碼分析

前言: 此源碼是作者根據(jù)上面的代碼示例一步一步跟進(jìn)去的,如果有哪些疑問(wèn)或者講的不正確的地方,請(qǐng)與作者聯(lián)系。

添加

添加的具體流程示意圖:

包括方法有:

add(E e)

add(int index, E element)

addAll(Collection c)

addAll(int index, Collection c)

addFirst(E e)

addLast(E e)

offer(E e)

offerFirst(E e)

offerLast(E e)

下面對(duì)這些方法逐個(gè)分析其源碼:

add(E e) :

        // 添加指定元素至list末尾
    public boolean add(E e) {
          linkLast(e);
          return true;
    }

        // 真正添加節(jié)點(diǎn)的操作
    void linkLast(E e) {
      final Node l = last;
        // 生成一個(gè)Node節(jié)點(diǎn)
      final Node newNode = new Node<>(l, e, null);
      last = newNode;
        // 如果l = null,代表的是第一個(gè)節(jié)點(diǎn),所以這個(gè)節(jié)點(diǎn)即是頭節(jié)點(diǎn)
        // 又是尾節(jié)點(diǎn)
      if (l == null)
          first = newNode;
      else
        // 如果不是的話,那么就讓該節(jié)點(diǎn)的next 指向新的節(jié)點(diǎn)
          l.next = newNode;
      size++;
      modCount++;
      }

比如第一次添加的是111,此時(shí)鏈表中還沒(méi)有節(jié)點(diǎn),所以此時(shí)的尾節(jié)點(diǎn)last 為null, 生成新的節(jié)點(diǎn),所以 此時(shí)的尾節(jié)點(diǎn)也就是111,所以這個(gè) 111 也是頭節(jié)點(diǎn),再進(jìn)行擴(kuò)容,修改次數(shù)對(duì)應(yīng)增加

第二次添加的是 222, 此時(shí)鏈表中已經(jīng)有了一個(gè)節(jié)點(diǎn),新添加的節(jié)點(diǎn)會(huì)添加到尾部,剛剛添加的111 就當(dāng)作頭節(jié)點(diǎn)來(lái)使用,222被添加到111的節(jié)點(diǎn)后面。

add(int index,E e) :

        /**
      *在指定位置插入指定的元素
      */
    public void add(int index, E element) {
        // 下標(biāo)檢查
        checkPositionIndex(index);

        if (index == size)
              // 如果需要插入的位置和鏈表的長(zhǎng)度相同,就在鏈表的最后添加
            linkLast(element);
        else
              // 否則就鏈接在此位置的前面
            linkBefore(element, node(index));
    }

    
        // 越界檢查
    private void checkPositionIndex(int index) {
          if (!isPositionIndex(index))
              throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

        // 判斷參數(shù)是否是有效位置(對(duì)于迭代或者添加操作來(lái)說(shuō))
        private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

        // linkLast 上面已經(jīng)介紹過(guò)

        // 查找索引所在的節(jié)點(diǎn)
        Node node(int index) {
        // assert isElementIndex(index);

        if (index < (size >> 1)) {
            Node x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

        // 在非空節(jié)點(diǎn)插入元素
        void linkBefore(E e, Node succ) {
        // assert succ != null;
          // succ 即是插入位置的節(jié)點(diǎn)
            // 查找該位置處的前面一個(gè)節(jié)點(diǎn)
        final Node pred = succ.prev;
        final Node newNode = new Node<>(pred, e, succ);
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }

例如在位置為1處添加值為123 的元素,首先對(duì)下標(biāo)進(jìn)行越界檢查,判斷這個(gè)位置是否等于鏈表的長(zhǎng)度,如果與鏈表長(zhǎng)度相同,就往最后插入,如果不同的話,就在索引的前面插入。

下標(biāo)為1 處并不等于索引的長(zhǎng)度,所以在索引前面插入,首先對(duì)查找 1 這個(gè)位置的節(jié)點(diǎn)是哪個(gè),并獲取這個(gè)節(jié)點(diǎn)的前面一個(gè)節(jié)點(diǎn),在判斷這個(gè)位置的前一個(gè)節(jié)點(diǎn)是否為null,如果是null,那么這個(gè)此處位置的元素就被當(dāng)作頭節(jié)點(diǎn),如果不是的話,頭節(jié)點(diǎn)的next 節(jié)點(diǎn)就指向123

addFirst(E e) :

        // 在頭節(jié)點(diǎn)插入元素
        public void addFirst(E e) {
        linkFirst(e);
    }

        
        private void linkFirst(E e) {
          // 先找到first 節(jié)點(diǎn)
        final Node f = first;
        final Node newNode = new Node<>(null, e, f);
        first = newNode;
        if (f == null)
              // f 為null,也就代表著沒(méi)有頭節(jié)點(diǎn)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }
例如要添加top 元素至鏈表的首部,需要先找到first節(jié)點(diǎn),如果first節(jié)點(diǎn)為null,也就說(shuō)明沒(méi)有頭節(jié)點(diǎn),如果不為null,則頭節(jié)點(diǎn)的prev節(jié)點(diǎn)是新插入的節(jié)點(diǎn)。

addLast(E e) :

        /**
        *     在末尾處添加節(jié)點(diǎn)
        */
        public void addLast(E e) {
        linkLast(e);
    }
        
        // 鏈接末尾處的節(jié)點(diǎn)
        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++;
    }
        
方法邏輯與在頭節(jié)點(diǎn)插入基本相同

addAll(Collections c) :

        /**
        * 在鏈表中批量添加數(shù)據(jù)
        */
        public boolean addAll(Collection c) {
        return addAll(size, c);
    }

        public boolean addAll(int index, Collection c) {
               // 越界檢查
        checkPositionIndex(index);
                
          // 把集合轉(zhuǎn)換為數(shù)組
        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;

        Node pred, succ;
          // 直接在末尾添加,所以index = size
        if (index == size) {
            succ = null;
            pred = last;
        } else {
            succ = node(index);
            pred = succ.prev;
        }
                
          // 遍歷每個(gè)數(shù)組
        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
              // 先對(duì)應(yīng)生成節(jié)點(diǎn),再進(jìn)行節(jié)點(diǎn)的鏈接
            Node newNode = new Node<>(pred, e, null);
            if (pred == null)
                first = newNode;
            else
                pred.next = newNode;
            pred = newNode;
        }

        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }
Collection collec = Arrays.asList("123","213","321");
list.addAll(collec);

例如要插入一個(gè)Collection為123,213,321 的集合,沒(méi)有指定插入元素的位置,默認(rèn)是向鏈表的尾部進(jìn)行鏈接,首先會(huì)進(jìn)行數(shù)組越界檢查,然后會(huì)把集合轉(zhuǎn)換為數(shù)組,在判斷數(shù)組的大小是否為0,為0返回,不為0,繼續(xù)下面操作

因?yàn)槭侵苯酉蜴溛膊迦?,所以index = size,然后遍歷每個(gè)數(shù)組,首先生成對(duì)應(yīng)的節(jié)點(diǎn),在對(duì)節(jié)點(diǎn)進(jìn)行鏈接,因?yàn)閟ucc 是null,此時(shí)last 節(jié)點(diǎn) = pred,這個(gè)時(shí)候的pred節(jié)點(diǎn)就是遍歷數(shù)組完成后的最后一個(gè)節(jié)點(diǎn)

然后再擴(kuò)容數(shù)組,增加修改次數(shù)

addAll(Collections c) : 這個(gè)方法的源碼同上

offer也是對(duì)元素進(jìn)行添加操作,源碼和add方法相同

offerFirst(E e)和addFirst(E e) 源碼相同

offerLast(E e)和addLast(E e) 源碼相同)

push(E e) 和addFirst(E e) 源碼相同

取出元素

包括方法有:

peek()

peekFirst()

peekLast()

element()

get(int index)

getFirst()

getLast()

indexOf(Object o)

lastIndexOf(Object o)

peek()

        /**
        *    只是訪問(wèn),但是不移除鏈表的頭元素
        */
        public E peek() {
        final Node f = first;
        return (f == null) ? null : f.item;
    }
peek() 源碼比較簡(jiǎn)單,直接找到鏈表的第一個(gè)節(jié)點(diǎn),判斷是否為null,如果為null,返回null,否則返回鏈?zhǔn)椎脑?/strong>

peekFirst() : 源碼和peek() 相同

peekLast():

        /**
        * 訪問(wèn),但是不移除鏈表中的最后一個(gè)元素
        * 或者返回null如果鏈表是空鏈表
        */
        public E peekLast() {
        final Node l = last;
        return (l == null) ? null : l.item;
    }
源碼也比較好理解

element() :

        /**
        * 只是訪問(wèn),但是不移除鏈表的第一個(gè)元素
        */
        public E element() {
        return getFirst();
    }

        public E getFirst() {
        final Node f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }
與peek()相同的地方都是訪問(wèn)鏈表的第一個(gè)元素,不同是element元素在鏈表為null的時(shí)候會(huì)報(bào)空指針異常

get(int index) :

        /*
        * 返回鏈表中指定位置的元素
        */ 
        public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

        // 返回指定索引下的元素的非空節(jié)點(diǎn)
        Node node(int index) {
        // assert isElementIndex(index);

        if (index < (size >> 1)) {
            Node x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }
get(int index)源碼也是比較好理解,首先對(duì)下標(biāo)進(jìn)行越界檢查,沒(méi)有越界的話直接找到索引位置對(duì)應(yīng)的node節(jié)點(diǎn),進(jìn)行返回

getFirst() :源碼和element()相同

getLast(): 直接找到最后一個(gè)元素進(jìn)行返回,和getFist幾乎相同

indexOf(Object o) :

        /*
        * 返回第一次出現(xiàn)指定元素的位置,或者-1如果不包含指定元素。
        */
        public int indexOf(Object o) {
        int index = 0;
        if (o == null) {
            for (Node x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            for (Node x = first; x != null; x = x.next) {
                if (o.equals(x.item))
                    return index;
                index++;
            }
        }
        return -1;
    }

兩種情況:

如果需要檢索的元素是null,對(duì)元素鏈表進(jìn)行遍歷,返回x的元素為空的位置

如果需要檢索的元素不是null,對(duì)元素的鏈表遍歷,直到找到相同的元素,返回元素下標(biāo)

lastIndexOf(Object o) :

        /*
        * 返回最后一次出現(xiàn)指定元素的位置,或者-1如果不包含指定元素。
        */
        public int lastIndexOf(Object o) {
        int index = size;
        if (o == null) {
            for (Node x = last; x != null; x = x.prev) {
                index--;
                if (x.item == null)
                    return index;
            }
        } else {
            for (Node x = last; x != null; x = x.prev) {
                index--;
                if (o.equals(x.item))
                    return index;
            }
        }
        return -1;
    }
從IndexOf(Object o)源碼反向理解

刪除

刪除節(jié)點(diǎn)的示意圖如下:

包括的方法有:

poll()

pollFirst()

pollLast()

pop()

remove()

remove(int index)

remove(Object o)

removeFirst()

removeFirstOccurrence(Object o)

removeLast()

removeLastOccurrence(Object o)

clear()

poll() :

        /*
        * 訪問(wèn)并移除鏈表中指定元素
        */
        public E poll() {
        final Node f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

        // 斷開(kāi)第一個(gè)非空節(jié)點(diǎn)
        private E unlinkFirst(Node f) {
        // assert f == first && f != null;
        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;
    }
poll()方法也比較簡(jiǎn)單直接,首先通過(guò)Node方法找到第一個(gè)鏈表頭,然后把鏈表的元素和鏈表頭指向的next元素置空,再把next節(jié)點(diǎn)的元素變?yōu)轭^節(jié)點(diǎn)的元素

pollFirst() : 與poll() 源碼相同

pollLast(): 與poll() 源碼很相似,不再解釋

pop()

            
    /*
        * 彈出鏈表的指定元素,換句話說(shuō),移除并返回鏈表中第一個(gè)元素
      */
    public E removeFirst() {
      final Node f = first;
      if (f == null)
        throw new NoSuchElementException();
      return unlinkFirst(f);
    }

    // unlinkFirst 源碼上面           
               
                                           
                       
                 

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/74072.html

相關(guān)文章

  • 我的阿里之路+Java面經(jīng)考點(diǎn)

    摘要:我的是忙碌的一年,從年初備戰(zhàn)實(shí)習(xí)春招,年三十都在死磕源碼,三月份經(jīng)歷了阿里五次面試,四月順利收到實(shí)習(xí)。因?yàn)槲倚睦砗芮宄?,我的目?biāo)是阿里。所以在收到阿里之后的那晚,我重新規(guī)劃了接下來(lái)的學(xué)習(xí)計(jì)劃,將我的短期目標(biāo)更新成拿下阿里轉(zhuǎn)正。 我的2017是忙碌的一年,從年初備戰(zhàn)實(shí)習(xí)春招,年三十都在死磕JDK源碼,三月份經(jīng)歷了阿里五次面試,四月順利收到實(shí)習(xí)offer。然后五月懷著忐忑的心情開(kāi)始了螞蟻金...

    姘擱『 評(píng)論0 收藏0
  • LinkedList源碼解析

    摘要:我們來(lái)看相關(guān)源碼我們看到封裝的和操作其實(shí)就是對(duì)頭結(jié)點(diǎn)的操作。迭代器通過(guò)指針,能指向下一個(gè)節(jié)點(diǎn),無(wú)需做額外的遍歷,速度非???。不同的遍歷性能差距極大,推薦使用迭代器進(jìn)行遍歷。LinkedList類介紹 上一篇文章我們介紹了JDK中ArrayList的實(shí)現(xiàn),ArrayList底層結(jié)構(gòu)是一個(gè)Object[]數(shù)組,通過(guò)拷貝,復(fù)制等一系列封裝的操作,將數(shù)組封裝為一個(gè)幾乎是無(wú)限的容器。今天我們來(lái)介紹JD...

    番茄西紅柿 評(píng)論0 收藏0
  • LinkedList源碼解析

    摘要:我們來(lái)看相關(guān)源碼我們看到封裝的和操作其實(shí)就是對(duì)頭結(jié)點(diǎn)的操作。迭代器通過(guò)指針,能指向下一個(gè)節(jié)點(diǎn),無(wú)需做額外的遍歷,速度非???。不同的遍歷性能差距極大,推薦使用迭代器進(jìn)行遍歷。LinkedList類介紹 上一篇文章我們介紹了JDK中ArrayList的實(shí)現(xiàn),ArrayList底層結(jié)構(gòu)是一個(gè)Object[]數(shù)組,通過(guò)拷貝,復(fù)制等一系列封裝的操作,將數(shù)組封裝為一個(gè)幾乎是無(wú)限的容器。今天我們來(lái)介紹JD...

    番茄西紅柿 評(píng)論0 收藏0
  • 類的加載機(jī)制 - 收藏集 - 掘金

    摘要:是現(xiàn)在廣泛流行的代從開(kāi)始學(xué)習(xí)系列之向提交代碼掘金讀完本文大概需要分鐘。為了進(jìn)行高效的垃圾回收,虛擬機(jī)把堆內(nèi)存劃分成新生代老年代和永久代中無(wú)永久代,使用實(shí)現(xiàn)三塊區(qū)域。 React Native 開(kāi)源項(xiàng)目 - 仿美團(tuán)客戶端 (Android、iOS 雙適配) - Android - 掘金推薦 React Native 學(xué)習(xí)好項(xiàng)目,仿照美團(tuán)客戶端... 極簡(jiǎn) GitHub 上手教程 - 工具...

    Gilbertat 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<