• Java重要类之LinkedList


    一、ArrayList与LinkedList

    基本概念:List是一个接口,Arraylist和LinkedList是它的两个实现类,只是实现的方式不一样。我在“单链表java实现”一文中已经对单链表的结构和基本方法进行了实现,这里要说的LinkedList是java封装好的双向链表数据结构,而ArrayList是用数组实现的,它不是真正的链表,在初始化的时候它先对数组设置一个初始容量,当数组空间不够的时候,它会重新构建一个容量更大的数组,然后把先前的元素拷贝进去。粗略的来讲,ArrayList和LinkedList本质上的区别就是数组和列表这两种数据结构的区别。

    大致区别:忽略特殊情况,一般来讲,两者有以下区别

    1.ArrayList是基于动态数组的数据结构,LinkedList基于链表的数据结构。 
    2.查找元素/读取
    数据:对于随机访问get和set,ArrayList性能优于LinkedList,ArrayList直接根据下标即可访问,而LinkedList遍历则要一步一步的移动指针。 
    3.新增/删除
    操作:add和remove,LinkedList比较占优势,其时间耗费仅仅在移动指针上。而ArrayList添加需要将后续元素后移,删除需要将后续元素前移,移动数据比较耗时。 

    LinkedList和ArrayList框架图

                                                

    二、LinkedList结构

    LinkedList是一种双向链表结构,如图所示。

    LinkedList包含两个重要的成员:header 和 size。header是双向链表的表头,它是双向链表节点所对应的类Entry的实例。size是双向链表中节点的个数。

    Entry中包含成员变量: previous, next, element。其中,previous是该节点的上一个节点,next是该节点的下一个节点,element是该节点所包含的值。 

    三、LinkedList API

    LinkedList 是一个继承于AbstractSequentialList的双向链表。它也可以被当作堆栈、队列或双端队列进行操作。

    LinkedList 实现 List 接口,能进行队列操作。

    LinkedList 实现 Deque 接口,即能将LinkedList当作双端队列使用。

     可以查看https://www.yiibai.com/java/util/详细说明

     1 LinkedList的API
     2 boolean       add(E object)  // 在链表/队列结尾添加元素
     3 void          add(int location, E object)  // 在指定位置添加元素
     4 boolean       addAll(Collection<? extends E> collection)  // 在链表结尾插入链表所有元素
     5 boolean       addAll(int location, Collection<? extends E> collection)   // 在链表指定位置插入链表所有元素
     6 void          addFirst(E object)  // 在链表开头添加元素
     7 void          addLast(E object)   // 在链表结尾添加元素
     8 void          clear()//清空链表
     9 Object        clone()//浅拷贝,与原链表共享对象
    10 boolean       contains(Object object) //是否包含某元素
    11 Iterator<E>   descendingIterator()  
    12 E             element()//返回此链表/队列第一个元素但不删除
    13 E             get(int location)//获取指定位置的元素
    14 E             getFirst()//返回此链表第一个元素
    15 E             getLast()//返回此链表最后一个元素
    16 int           indexOf(Object object)//返回指定元素的第一个匹配项的索引在此列表中,或者如果此列表中不包含该元素返回-1
    17 int           lastIndexOf(Object object)//返回指定元素的最后一个匹配项的索引在此列表中,或者如果此列表中不包含该元素返回-1
    18 ListIterator<E>     listIterator(int location)
    19 boolean       offer(E o) // 在队列的末尾插入指定的元素
    20 boolean       offerFirst(E e) // 在此列表的开头插入指定的元素
    21 boolean       offerLast(E e)// 在此列表的末尾插入指定的元素
    22 E             peek()//访问此链表/列表/栈第一个元素但不删除
    23 E             peekFirst()//返回此链表第一个元素但不删除
    24 E             peekLast()//返回此链表最后一个元素但不删除
    25 E             poll()//检索并移除头部
    26 E             pollFirst()//检索并移除头部
    27 E pollLast()//检索并移除最后一个元素 28 E pop() // 从此列表所表示的堆栈处弹出一个元素(获取并移除列表第一个元素) 29 void push(E e) // 将元素推入此列表所表示的堆栈(插入到列表的头) 30 E remove() //删除队列第一个元素 31 E remove(int location)//删除指定位置的元素 32 boolean remove(Object object)//删除指定元素 33 E removeFirst() // 从此列表中移除第一个元素
    34 boolean removeFirstOccurrence(Object o) // 从此列表中移除第一次出现的指定元素(从头部到尾部遍历列表) 35 E removeLast()// 从此列表中移除最后一个元素 36 boolean removeLastOccurrence(Object o) // 从此列表中移除第一次出现的指定元素(从头部到尾部遍历列表) 37 E set(int location, E object) // 将此列表中指定位置的元素替换为指定的元素 38 int size()//链表大小 39 <T> T[] toArray(T[] contents) 40 Object[] toArray()//返回一个包含所有在此列表的正确顺序的元素的数组。

     总结:

    ·LinkedList可以作为FIFO(先进先出)的队列,作为FIFO的队列时,下表的方法等价:

    队列方法       等效方法
    add(e)        addLast(e)
    offer(e)      offerLast(e)
    remove()      removeFirst()
    poll()        pollFirst()
    element()     getFirst()
    peek()        peekFirst()

    ·LinkedList可以作为LIFO(后进先出)的栈,作为LIFO的栈时,下表的方法等价:

    栈方法        等效方法
    push(e)      addFirst(e)
    pop()        removeFirst()
    peek()       peekFirst()

    四、LinkedList的遍历方式

    1、迭代器遍历

    1 Iterator<Integer> iterator = linkedList.iterator();
    2 while(iterator.hasNext()){
    3     iterator.next();
    4 }

    2、get遍历

    对linkedList进行顺序遍历速度较慢,每一次get都需要从头开始搜索

    1 for(int i = 0; i < linkedList.size(); i++){
    2     linkedList.get(i);
    3 }

    3、for遍历

    1 for(Integer i:linklist){
    2     System.out.println(i);
    3 }

    4、遍历的同时删除元素

    1 while(linklist.size() != 0){
    2     linklist.pollFirst();          // linklist.pollLast();
    3 }
    1 while(linklist.size() != 0){
    2     linklist.removeFirst();       // linklist.removeLast(); 
    3 }

    综上以上几种方式,第2种效率最低,尽量不采用。如果是单纯的访问元素,避免对原链表的修改,则使用方式1或3。注意:方式4在访问链表元素的同时会删除元素。

    五、LinkedList源码

    具体说明参考博客https://blog.csdn.net/qq_19431333/article/details/54572876

      1 package java.util;
      2 
      3 public class LinkedList<E>
      4     extends AbstractSequentialList<E>
      5     implements List<E>, Deque<E>, Cloneable, java.io.Serializable
      6 {
      7     // 链表的表头,表头不包含任何数据。Entry是个链表类数据结构。
      8     private transient Entry<E> header = new Entry<E>(null, null, null);
      9 
     10     // LinkedList中元素个数
     11     private transient int size = 0;
     12 
     13     // 默认构造函数:创建一个空的链表
     14     public LinkedList() {
     15         header.next = header.previous = header;
     16     }
     17 
     18     // 包含“集合”的构造函数:创建一个包含“集合”的LinkedList
     19     public LinkedList(Collection<? extends E> c) {
     20         this();
     21         addAll(c);
     22     }
     23 
     24     // 获取LinkedList的第一个元素
     25     public E getFirst() {
     26         if (size==0)
     27             throw new NoSuchElementException();
     28 
     29         // 链表的表头header中不包含数据。
     30         // 这里返回header所指下一个节点所包含的数据。
     31         return header.next.element;
     32     }
     33 
     34     // 获取LinkedList的最后一个元素
     35     public E getLast()  {
     36         if (size==0)
     37             throw new NoSuchElementException();
     38 
     39         // 由于LinkedList是双向链表;而表头header不包含数据。
     40         // 因而,这里返回表头header的前一个节点所包含的数据。
     41         return header.previous.element;
     42     }
     43 
     44     // 删除LinkedList的第一个元素
     45     public E removeFirst() {
     46         return remove(header.next);
     47     }
     48 
     49     // 删除LinkedList的最后一个元素
     50     public E removeLast() {
     51         return remove(header.previous);
     52     }
     53 
     54     // 将元素添加到LinkedList的起始位置
     55     public void addFirst(E e) {
     56         addBefore(e, header.next);
     57     }
     58 
     59     // 将元素添加到LinkedList的结束位置
     60     public void addLast(E e) {
     61         addBefore(e, header);
     62     }
     63 
     64     // 判断LinkedList是否包含元素(o)
     65     public boolean contains(Object o) {
     66         return indexOf(o) != -1;
     67     }
     68 
     69     // 返回LinkedList的大小
     70     public int size() {
     71         return size;
     72     }
     73 
     74     // 将元素(E)添加到LinkedList中
     75     public boolean add(E e) {
     76         // 将节点(节点数据是e)添加到表头(header)之前。
     77         // 即,将节点添加到双向链表的末端。
     78         addBefore(e, header);
     79         return true;
     80     }
     81 
     82     // 从LinkedList中删除元素(o)
     83     // 从链表开始查找,如存在元素(o)则删除该元素并返回true;
     84     // 否则,返回false。
     85     public boolean remove(Object o) {
     86         if (o==null) {
     87             // 若o为null的删除情况
     88             for (Entry<E> e = header.next; e != header; e = e.next) {
     89                 if (e.element==null) {
     90                     remove(e);
     91                     return true;
     92                 }
     93             }
     94         } else {
     95             // 若o不为null的删除情况
     96             for (Entry<E> e = header.next; e != header; e = e.next) {
     97                 if (o.equals(e.element)) {
     98                     remove(e);
     99                     return true;
    100                 }
    101             }
    102         }
    103         return false;
    104     }
    105 
    106     // 将“集合(c)”添加到LinkedList中。
    107     // 实际上,是从双向链表的末尾开始,将“集合(c)”添加到双向链表中。
    108     public boolean addAll(Collection<? extends E> c) {
    109         return addAll(size, c);
    110     }
    111 
    112     // 从双向链表的index开始,将“集合(c)”添加到双向链表中。
    113     public boolean addAll(int index, Collection<? extends E> c) {
    114         if (index < 0 || index > size)
    115             throw new IndexOutOfBoundsException("Index: "+index+
    116                                                 ", Size: "+size);
    117         Object[] a = c.toArray();
    118         // 获取集合的长度
    119         int numNew = a.length;
    120         if (numNew==0)
    121             return false;
    122         modCount++;
    123 
    124         // 设置“当前要插入节点的后一个节点”
    125         Entry<E> successor = (index==size ? header : entry(index));
    126         // 设置“当前要插入节点的前一个节点”
    127         Entry<E> predecessor = successor.previous;
    128         // 将集合(c)全部插入双向链表中
    129         for (int i=0; i<numNew; i++) {
    130             Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);
    131             predecessor.next = e;
    132             predecessor = e;
    133         }
    134         successor.previous = predecessor;
    135 
    136         // 调整LinkedList的实际大小
    137         size += numNew;
    138         return true;
    139     }
    140 
    141     // 清空双向链表
    142     public void clear() {
    143         Entry<E> e = header.next;
    144         // 从表头开始,逐个向后遍历;对遍历到的节点执行一下操作:
    145         // (01) 设置前一个节点为null 
    146         // (02) 设置当前节点的内容为null 
    147         // (03) 设置后一个节点为“新的当前节点”
    148         while (e != header) {
    149             Entry<E> next = e.next;
    150             e.next = e.previous = null;
    151             e.element = null;
    152             e = next;
    153         }
    154         header.next = header.previous = header;
    155         // 设置大小为0
    156         size = 0;
    157         modCount++;
    158     }
    159 
    160     // 返回LinkedList指定位置的元素
    161     public E get(int index) {
    162         return entry(index).element;
    163     }
    164 
    165     // 设置index位置对应的节点的值为element
    166     public E set(int index, E element) {
    167         Entry<E> e = entry(index);
    168         E oldVal = e.element;
    169         e.element = element;
    170         return oldVal;
    171     }
    172  
    173     // 在index前添加节点,且节点的值为element
    174     public void add(int index, E element) {
    175         addBefore(element, (index==size ? header : entry(index)));
    176     }
    177 
    178     // 删除index位置的节点
    179     public E remove(int index) {
    180         return remove(entry(index));
    181     }
    182 
    183     // 获取双向链表中指定位置的节点
    184     private Entry<E> entry(int index) {
    185         if (index < 0 || index >= size)
    186             throw new IndexOutOfBoundsException("Index: "+index+
    187                                                 ", Size: "+size);
    188         Entry<E> e = header;
    189         // 获取index处的节点。
    190         // 若index < 双向链表长度的1/2,则从前先后查找;
    191         // 否则,从后向前查找。
    192         if (index < (size >> 1)) {
    193             for (int i = 0; i <= index; i++)
    194                 e = e.next;
    195         } else {
    196             for (int i = size; i > index; i--)
    197                 e = e.previous;
    198         }
    199         return e;
    200     }
    201 
    202     // 从前向后查找,返回“值为对象(o)的节点对应的索引”
    203     // 不存在就返回-1
    204     public int indexOf(Object o) {
    205         int index = 0;
    206         if (o==null) {
    207             for (Entry e = header.next; e != header; e = e.next) {
    208                 if (e.element==null)
    209                     return index;
    210                 index++;
    211             }
    212         } else {
    213             for (Entry e = header.next; e != header; e = e.next) {
    214                 if (o.equals(e.element))
    215                     return index;
    216                 index++;
    217             }
    218         }
    219         return -1;
    220     }
    221 
    222     // 从后向前查找,返回“值为对象(o)的节点对应的索引”
    223     // 不存在就返回-1
    224     public int lastIndexOf(Object o) {
    225         int index = size;
    226         if (o==null) {
    227             for (Entry e = header.previous; e != header; e = e.previous) {
    228                 index--;
    229                 if (e.element==null)
    230                     return index;
    231             }
    232         } else {
    233             for (Entry e = header.previous; e != header; e = e.previous) {
    234                 index--;
    235                 if (o.equals(e.element))
    236                     return index;
    237             }
    238         }
    239         return -1;
    240     }
    241 
    242     // 返回第一个节点
    243     // 若LinkedList的大小为0,则返回null
    244     public E peek() {
    245         if (size==0)
    246             return null;
    247         return getFirst();
    248     }
    249 
    250     // 返回第一个节点
    251     // 若LinkedList的大小为0,则抛出异常
    252     public E element() {
    253         return getFirst();
    254     }
    255 
    256     // 删除并返回第一个节点
    257     // 若LinkedList的大小为0,则返回null
    258     public E poll() {
    259         if (size==0)
    260             return null;
    261         return removeFirst();
    262     }
    263 
    264     // 将e添加双向链表末尾
    265     public boolean offer(E e) {
    266         return add(e);
    267     }
    268 
    269     // 将e添加双向链表开头
    270     public boolean offerFirst(E e) {
    271         addFirst(e);
    272         return true;
    273     }
    274 
    275     // 将e添加双向链表末尾
    276     public boolean offerLast(E e) {
    277         addLast(e);
    278         return true;
    279     }
    280 
    281     // 返回第一个节点
    282     // 若LinkedList的大小为0,则返回null
    283     public E peekFirst() {
    284         if (size==0)
    285             return null;
    286         return getFirst();
    287     }
    288 
    289     // 返回最后一个节点
    290     // 若LinkedList的大小为0,则返回null
    291     public E peekLast() {
    292         if (size==0)
    293             return null;
    294         return getLast();
    295     }
    296 
    297     // 删除并返回第一个节点
    298     // 若LinkedList的大小为0,则返回null
    299     public E pollFirst() {
    300         if (size==0)
    301             return null;
    302         return removeFirst();
    303     }
    304 
    305     // 删除并返回最后一个节点
    306     // 若LinkedList的大小为0,则返回null
    307     public E pollLast() {
    308         if (size==0)
    309             return null;
    310         return removeLast();
    311     }
    312 
    313     // 将e插入到双向链表开头
    314     public void push(E e) {
    315         addFirst(e);
    316     }
    317 
    318     // 删除并返回第一个节点
    319     public E pop() {
    320         return removeFirst();
    321     }
    322 
    323     // 从LinkedList开始向后查找,删除第一个值为元素(o)的节点
    324     // 从链表开始查找,如存在节点的值为元素(o)的节点,则删除该节点
    325     public boolean removeFirstOccurrence(Object o) {
    326         return remove(o);
    327     }
    328 
    329     // 从LinkedList末尾向前查找,删除第一个值为元素(o)的节点
    330     // 从链表开始查找,如存在节点的值为元素(o)的节点,则删除该节点
    331     public boolean removeLastOccurrence(Object o) {
    332         if (o==null) {
    333             for (Entry<E> e = header.previous; e != header; e = e.previous) {
    334                 if (e.element==null) {
    335                     remove(e);
    336                     return true;
    337                 }
    338             }
    339         } else {
    340             for (Entry<E> e = header.previous; e != header; e = e.previous) {
    341                 if (o.equals(e.element)) {
    342                     remove(e);
    343                     return true;
    344                 }
    345             }
    346         }
    347         return false;
    348     }
    349 
    350     // 返回“index到末尾的全部节点”对应的ListIterator对象(List迭代器)
    351     public ListIterator<E> listIterator(int index) {
    352         return new ListItr(index);
    353     }
    354 
    355     // List迭代器
    356     private class ListItr implements ListIterator<E> {
    357         // 上一次返回的节点
    358         private Entry<E> lastReturned = header;
    359         // 下一个节点
    360         private Entry<E> next;
    361         // 下一个节点对应的索引值
    362         private int nextIndex;
    363         // 期望的改变计数。用来实现fail-fast机制。
    364         private int expectedModCount = modCount;
    365 
    366         // 构造函数。
    367         // 从index位置开始进行迭代
    368         ListItr(int index) {
    369             // index的有效性处理
    370             if (index < 0 || index > size)
    371                 throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size);
    372             // 若 “index 小于 ‘双向链表长度的一半’”,则从第一个元素开始往后查找;
    373             // 否则,从最后一个元素往前查找。
    374             if (index < (size >> 1)) {
    375                 next = header.next;
    376                 for (nextIndex=0; nextIndex<index; nextIndex++)
    377                     next = next.next;
    378             } else {
    379                 next = header;
    380                 for (nextIndex=size; nextIndex>index; nextIndex--)
    381                     next = next.previous;
    382             }
    383         }
    384 
    385         // 是否存在下一个元素
    386         public boolean hasNext() {
    387             // 通过元素索引是否等于“双向链表大小”来判断是否达到最后。
    388             return nextIndex != size;
    389         }
    390 
    391         // 获取下一个元素
    392         public E next() {
    393             checkForComodification();
    394             if (nextIndex == size)
    395                 throw new NoSuchElementException();
    396 
    397             lastReturned = next;
    398             // next指向链表的下一个元素
    399             next = next.next;
    400             nextIndex++;
    401             return lastReturned.element;
    402         }
    403 
    404         // 是否存在上一个元素
    405         public boolean hasPrevious() {
    406             // 通过元素索引是否等于0,来判断是否达到开头。
    407             return nextIndex != 0;
    408         }
    409 
    410         // 获取上一个元素
    411         public E previous() {
    412             if (nextIndex == 0)
    413             throw new NoSuchElementException();
    414 
    415             // next指向链表的上一个元素
    416             lastReturned = next = next.previous;
    417             nextIndex--;
    418             checkForComodification();
    419             return lastReturned.element;
    420         }
    421 
    422         // 获取下一个元素的索引
    423         public int nextIndex() {
    424             return nextIndex;
    425         }
    426 
    427         // 获取上一个元素的索引
    428         public int previousIndex() {
    429             return nextIndex-1;
    430         }
    431 
    432         // 删除当前元素。
    433         // 删除双向链表中的当前节点
    434         public void remove() {
    435             checkForComodification();
    436             Entry<E> lastNext = lastReturned.next;
    437             try {
    438                 LinkedList.this.remove(lastReturned);
    439             } catch (NoSuchElementException e) {
    440                 throw new IllegalStateException();
    441             }
    442             if (next==lastReturned)
    443                 next = lastNext;
    444             else
    445                 nextIndex--;
    446             lastReturned = header;
    447             expectedModCount++;
    448         }
    449 
    450         // 设置当前节点为e
    451         public void set(E e) {
    452             if (lastReturned == header)
    453                 throw new IllegalStateException();
    454             checkForComodification();
    455             lastReturned.element = e;
    456         }
    457 
    458         // 将e添加到当前节点的前面
    459         public void add(E e) {
    460             checkForComodification();
    461             lastReturned = header;
    462             addBefore(e, next);
    463             nextIndex++;
    464             expectedModCount++;
    465         }
    466 
    467         // 判断 “modCount和expectedModCount是否相等”,依次来实现fail-fast机制。
    468         final void checkForComodification() {
    469             if (modCount != expectedModCount)
    470             throw new ConcurrentModificationException();
    471         }
    472     }
    473 
    474     // 双向链表的节点所对应的数据结构。
    475     // 包含3部分:上一节点,下一节点,当前节点值。
    476     private static class Entry<E> {
    477         // 当前节点所包含的值
    478         E element;
    479         // 下一个节点
    480         Entry<E> next;
    481         // 上一个节点
    482         Entry<E> previous;
    483 
    484         /**
    485          * 链表节点的构造函数。
    486          * 参数说明:
    487          *   element  —— 节点所包含的数据
    488          *   next      —— 下一个节点
    489          *   previous —— 上一个节点
    490          */
    491         Entry(E element, Entry<E> next, Entry<E> previous) {
    492             this.element = element;
    493             this.next = next;
    494             this.previous = previous;
    495         }
    496     }
    497 
    498     // 将节点(节点数据是e)添加到entry节点之前。
    499     private Entry<E> addBefore(E e, Entry<E> entry) {
    500         // 新建节点newEntry,将newEntry插入到节点e之前;并且设置newEntry的数据是e
    501         Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
    502         newEntry.previous.next = newEntry;
    503         newEntry.next.previous = newEntry;
    504         // 修改LinkedList大小
    505         size++;
    506         // 修改LinkedList的修改统计数:用来实现fail-fast机制。
    507         modCount++;
    508         return newEntry;
    509     }
    510 
    511     // 将节点从链表中删除
    512     private E remove(Entry<E> e) {
    513         if (e == header)
    514             throw new NoSuchElementException();
    515 
    516         E result = e.element;
    517         e.previous.next = e.next;
    518         e.next.previous = e.previous;
    519         e.next = e.previous = null;
    520         e.element = null;
    521         size--;
    522         modCount++;
    523         return result;
    524     }
    525 
    526     // 反向迭代器
    527     public Iterator<E> descendingIterator() {
    528         return new DescendingIterator();
    529     }
    530 
    531     // 反向迭代器实现类。
    532     private class DescendingIterator implements Iterator {
    533         final ListItr itr = new ListItr(size());
    534         // 反向迭代器是否下一个元素。
    535         // 实际上是判断双向链表的当前节点是否达到开头
    536         public boolean hasNext() {
    537             return itr.hasPrevious();
    538         }
    539         // 反向迭代器获取下一个元素。
    540         // 实际上是获取双向链表的前一个节点
    541         public E next() {
    542             return itr.previous();
    543         }
    544         // 删除当前节点
    545         public void remove() {
    546             itr.remove();
    547         }
    548     }
    549 
    550 
    551     // 返回LinkedList的Object[]数组
    552     public Object[] toArray() {
    553     // 新建Object[]数组
    554     Object[] result = new Object[size];
    555         int i = 0;
    556         // 将链表中所有节点的数据都添加到Object[]数组中
    557         for (Entry<E> e = header.next; e != header; e = e.next)
    558             result[i++] = e.element;
    559     return result;
    560     }
    561 
    562     // 返回LinkedList的模板数组。所谓模板数组,即可以将T设为任意的数据类型
    563     public <T> T[] toArray(T[] a) {
    564         // 若数组a的大小 < LinkedList的元素个数(意味着数组a不能容纳LinkedList中全部元素)
    565         // 则新建一个T[]数组,T[]的大小为LinkedList大小,并将该T[]赋值给a。
    566         if (a.length < size)
    567             a = (T[])java.lang.reflect.Array.newInstance(
    568                                 a.getClass().getComponentType(), size);
    569         // 将链表中所有节点的数据都添加到数组a中
    570         int i = 0;
    571         Object[] result = a;
    572         for (Entry<E> e = header.next; e != header; e = e.next)
    573             result[i++] = e.element;
    574 
    575         if (a.length > size)
    576             a[size] = null;
    577 
    578         return a;
    579     }
    580 
    581 
    582     // 克隆函数。返回LinkedList的克隆对象。
    583     public Object clone() {
    584         LinkedList<E> clone = null;
    585         // 克隆一个LinkedList克隆对象
    586         try {
    587             clone = (LinkedList<E>) super.clone();
    588         } catch (CloneNotSupportedException e) {
    589             throw new InternalError();
    590         }
    591 
    592         // 新建LinkedList表头节点
    593         clone.header = new Entry<E>(null, null, null);
    594         clone.header.next = clone.header.previous = clone.header;
    595         clone.size = 0;
    596         clone.modCount = 0;
    597 
    598         // 将链表中所有节点的数据都添加到克隆对象中
    599         for (Entry<E> e = header.next; e != header; e = e.next)
    600             clone.add(e.element);
    601 
    602         return clone;
    603     }
    604 
    605     // java.io.Serializable的写入函数
    606     // 将LinkedList的“容量,所有的元素值”都写入到输出流中
    607     private void writeObject(java.io.ObjectOutputStream s)
    608         throws java.io.IOException {
    609         // Write out any hidden serialization magic
    610         s.defaultWriteObject();
    611 
    612         // 写入“容量”
    613         s.writeInt(size);
    614 
    615         // 将链表中所有节点的数据都写入到输出流中
    616         for (Entry e = header.next; e != header; e = e.next)
    617             s.writeObject(e.element);
    618     }
    619 
    620     // java.io.Serializable的读取函数:根据写入方式反向读出
    621     // 先将LinkedList的“容量”读出,然后将“所有的元素值”读出
    622     private void readObject(java.io.ObjectInputStream s)
    623         throws java.io.IOException, ClassNotFoundException {
    624         // Read in any hidden serialization magic
    625         s.defaultReadObject();
    626 
    627         // 从输入流中读取“容量”
    628         int size = s.readInt();
    629 
    630         // 新建链表表头节点
    631         header = new Entry<E>(null, null, null);
    632         header.next = header.previous = header;
    633 
    634         // 从输入流中将“所有的元素值”并逐个添加到链表中
    635         for (int i=0; i<size; i++)
    636             addBefore((E)s.readObject(), header);
    637     }
    638 
    639 }
    View Code

     六、实例

      1 import java.util.Iterator;
      2 import java.util.LinkedList;
      3
      4 public class LinkedListDemo {
      5     public static void main(String[] srgs){
      6         LinkedList<Integer> linkedList = new LinkedList<>();
      7 
      8         /************************** 基本操作 ************************/
      9         linkedList.addFirst(0);    // 添加元素到列表开头
     10         linkedList.add(1);         // 在列表结尾添加元素
     11         linkedList.add(2,2);       // 在指定位置添加元素
     12         linkedList.addLast(3);     // 添加元素到列表结尾
     13 
     14         System.out.println("LinkedList: " + linkedList);
     15 
     16         System.out.println("getFirst(): " + linkedList.getFirst());       // 返回此列表的第一个元素
     17         System.out.println("getLast(): " + linkedList.getLast());         // 返回此列表的最后一个元素       
     18         System.out.println("removeFirst(): " + linkedList.removeFirst()); // 移除并返回此列表的第一个元素     
     19         System.out.println("removeLast(): " + linkedList.removeLast());   // 移除并返回此列表的最后一个元素
     20         System.out.println("After remove:" + linkedList);                   
     21         System.out.println("contains(1) is :" + linkedList.contains(1));  // 判断此列表包含指定元素,如果是,则返回true    
     22         System.out.println("size is : " + linkedList.size());             // 返回此列表的元素个数
     23 
     24         /************************** 位置访问操作 ************************/
     25         System.out.println("-----------------------------------------");
     26         linkedList.set(1, 3);                                             // 将此列表中指定位置的元素替换为指定的元素
     27         System.out.println("After set(1, 3):" + linkedList);  
     28         System.out.println("get(1): " + linkedList.get(1));               // 返回此列表中指定位置处的元素
     29 
     30         /************************** Search操作  ************************/
     31         System.out.println("-----------------------------------------");
     32         linkedList.add(3);
     33         System.out.println("indexOf(3): " + linkedList.indexOf(3));        // 返回此列表中首次出现的指定元素的索引
     34         System.out.println("lastIndexOf(3): " + linkedList.lastIndexOf(3));// 返回此列表中最后出现的指定元素的索引
     35 
     36         /************************** Queue操作   队头出,队尾进************************/
     37         System.out.println("-----------------------------------------");
     38         System.out.println("peek(): " + linkedList.peek());                // 获取但不移除此列表的头
     39         System.out.println("element(): " + linkedList.element());          // 获取但不移除此列表的头
     40         linkedList.poll();                                                 // 获取并移除此列表的头
     41         System.out.println("After poll():" + linkedList);
     42         linkedList.remove();
     43         System.out.println("After remove():" + linkedList);                // 获取并移除此列表的头
     44         linkedList.offer(4);
     45         System.out.println("After offer(4):" + linkedList);                // 将指定元素添加到此列表的末尾  
     46 
     47         /************************** Deque操作   双端队列(栈+队列)************************/
     48         System.out.println("-----------------------------------------");
     49         linkedList.offerFirst(2);                                          // 在此列表的开头插入指定的元素
     50         System.out.println("After offerFirst(2):" + linkedList);
     51         linkedList.offerLast(5);                                           // 在此列表末尾插入指定的元素
     52         System.out.println("After offerLast(5):" + linkedList);
     53         System.out.println("peekFirst(): " + linkedList.peekFirst());      // 获取但不移除此列表的第一个元素
     54         System.out.println("peekLast(): " + linkedList.peekLast());        // 获取但不移除此列表的第一个元素
     55         linkedList.pollFirst();                                            // 获取并移除此列表的第一个元素
     56         System.out.println("After pollFirst():" + linkedList);
     57         linkedList.pollLast();                                             // 获取并移除此列表的最后一个元素
     58         System.out.println("After pollLast():" + linkedList);
     59         linkedList.push(2);                                                // 将元素推入此列表所表示的堆栈(插入到列表的头)
     60         System.out.println("After push(2):" + linkedList);
     61         linkedList.pop();                                                  // 从此列表所表示的堆栈处弹出一个元素(获取并移除列表第一个元素)
     62         System.out.println("After pop():" + linkedList);
     63         linkedList.add(3);
     64         linkedList.removeFirstOccurrence(3);                               // 从此列表中移除第一次出现的指定元素(从头部到尾部遍历列表)
     65         System.out.println("After removeFirstOccurrence(3):" + linkedList);
     66         linkedList.removeLastOccurrence(3);                                // 从此列表中移除最后一次出现的指定元素(从头部到尾部遍历列表)
     67         System.out.println("After removeFirstOccurrence(3):" + linkedList);
     68 
     69         /************************** 遍历操作   ************************/
     70         System.out.println("-----------------------------------------");
     71         linkedList.clear();
     72         for(int i = 0; i < 100000; i++){
     73             linkedList.add(i);
     74         }
     75         // 迭代器遍历
     76         long start = System.currentTimeMillis();
     77         Iterator<Integer> iterator = linkedList.iterator();
     78         while(iterator.hasNext()){
     79             iterator.next();
     80         }
     81         long end = System.currentTimeMillis();
     82         System.out.println("Iterator:" + (end - start) +" ms");
     83 
     84         // 顺序遍历(随机遍历)
     85         start = System.currentTimeMillis();
     86         for(int i = 0; i < linkedList.size(); i++){
     87             linkedList.get(i);
     88         }
     89         end = System.currentTimeMillis();
     90         System.out.println("for:" + (end - start) +" ms");
     91 
     92         // for遍历
     93         start = System.currentTimeMillis();
     94         for(Integer i : linkedList);
     95         end = System.currentTimeMillis();
     96         System.out.println("for2:" + (end - start) +" ms");
     97 
     98         //  通过pollFirst()或pollLast()来遍历LinkedList
     99         LinkedList<Integer> temp1 = new LinkedList<>();
    100         temp1.addAll(linkedList);
    101         start = System.currentTimeMillis();
    102         while(temp1.size() != 0){
    103             temp1.pollFirst();
    104         }
    105         end = System.currentTimeMillis();
    106         System.out.println("pollFirst()或pollLast():" + (end - start) +" ms");
    107 
    108         // 通过removeFirst()或removeLast()来遍历LinkedList
    109         LinkedList<Integer> temp2 = new LinkedList<>();
    110         temp2.addAll(linkedList);
    111         start = System.currentTimeMillis();
    112         while(temp2.size() != 0){
    113             temp2.removeFirst();
    114         }
    115         end = System.currentTimeMillis();
    116         System.out.println("removeFirst()或removeLast():" + (end - start) +" ms");
    117     }
    118 }
    119 /**Output
    120 LinkedList: [0, 1, 2, 3]
    121 getFirst(): 0
    122 getLast(): 3
    123 removeFirst(): 0
    124 removeLast(): 3
    125 After remove:[1, 2]
    126 contains(1) is :true
    127 size is : 2
    128 -----------------------------------------
    129 After set(1, 3):[1, 3]
    130 get(1): 3
    131 -----------------------------------------
    132 indexOf(3): 1
    133 lastIndexOf(3): 2
    134 -----------------------------------------
    135 peek(): 1
    136 element(): 1
    137 After poll():[3, 3]
    138 After remove():[3]
    139 After offer(4):[3, 4]
    140 -----------------------------------------
    141 After offerFirst(2):[2, 3, 4]
    142 After offerLast(5):[2, 3, 4, 5]
    143 peekFirst(): 2
    144 peekLast(): 5
    145 After pollFirst():[3, 4, 5]
    146 After pollLast():[3, 4]
    147 After push(2):[2, 3, 4]
    148 After pop():[3, 4]
    149 After removeFirstOccurrence(3):[4, 3]
    150 After removeFirstOccurrence(3):[4]
    151 -----------------------------------------
    152 Iterator:17 ms
    153 for:8419 ms
    154 for2:12 ms
    155 pollFirst()或pollLast():12 ms
    156 removeFirst()或removeLast():10 ms
    157 */

     参考自:https://blog.csdn.net/gongchuangsu/article/details/51527042

  • 相关阅读:
    查看程序设计语言排行榜的网站
    转:Android开发实践:用脚本编译Android工程
    ant 自动构建血泪史
    Android ant自动打包 crunch 报错
    android strings.xml 报 is not translated in af,
    HDU 5319
    hdu4405--Aeroplane chess(概率dp第七弹:飞行棋游戏--2012年网络赛)
    Linux 截图
    西工大10级保研机试 柱状图
    Codeforces Round #256 (Div. 2) B. Suffix Structures(模拟)
  • 原文地址:https://www.cnblogs.com/darlinFly/p/9327729.html
Copyright © 2020-2023  润新知