rt/emul/compact/src/main/java/java/util/LinkedList.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 26 Feb 2013 16:54:16 +0100
changeset 772 d382dacfd73f
parent 599 emul/compact/src/main/java/java/util/LinkedList.java@d0f57d3ea898
permissions -rw-r--r--
Moving modules around so the runtime is under one master pom and can be built without building other modules that are in the repository
jaroslav@597
     1
/*
jaroslav@597
     2
 * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
jaroslav@597
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@597
     4
 *
jaroslav@597
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@597
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@597
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@597
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@597
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@597
    10
 *
jaroslav@597
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@597
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@597
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@597
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@597
    15
 * accompanied this code).
jaroslav@597
    16
 *
jaroslav@597
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@597
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@597
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@597
    20
 *
jaroslav@597
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@597
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@597
    23
 * questions.
jaroslav@597
    24
 */
jaroslav@597
    25
jaroslav@597
    26
package java.util;
jaroslav@597
    27
jaroslav@597
    28
/**
jaroslav@597
    29
 * Doubly-linked list implementation of the {@code List} and {@code Deque}
jaroslav@597
    30
 * interfaces.  Implements all optional list operations, and permits all
jaroslav@597
    31
 * elements (including {@code null}).
jaroslav@597
    32
 *
jaroslav@597
    33
 * <p>All of the operations perform as could be expected for a doubly-linked
jaroslav@597
    34
 * list.  Operations that index into the list will traverse the list from
jaroslav@597
    35
 * the beginning or the end, whichever is closer to the specified index.
jaroslav@597
    36
 *
jaroslav@597
    37
 * <p><strong>Note that this implementation is not synchronized.</strong>
jaroslav@597
    38
 * If multiple threads access a linked list concurrently, and at least
jaroslav@597
    39
 * one of the threads modifies the list structurally, it <i>must</i> be
jaroslav@597
    40
 * synchronized externally.  (A structural modification is any operation
jaroslav@597
    41
 * that adds or deletes one or more elements; merely setting the value of
jaroslav@597
    42
 * an element is not a structural modification.)  This is typically
jaroslav@597
    43
 * accomplished by synchronizing on some object that naturally
jaroslav@597
    44
 * encapsulates the list.
jaroslav@597
    45
 *
jaroslav@597
    46
 * If no such object exists, the list should be "wrapped" using the
jaroslav@597
    47
 * {@link Collections#synchronizedList Collections.synchronizedList}
jaroslav@597
    48
 * method.  This is best done at creation time, to prevent accidental
jaroslav@597
    49
 * unsynchronized access to the list:<pre>
jaroslav@597
    50
 *   List list = Collections.synchronizedList(new LinkedList(...));</pre>
jaroslav@597
    51
 *
jaroslav@597
    52
 * <p>The iterators returned by this class's {@code iterator} and
jaroslav@597
    53
 * {@code listIterator} methods are <i>fail-fast</i>: if the list is
jaroslav@597
    54
 * structurally modified at any time after the iterator is created, in
jaroslav@597
    55
 * any way except through the Iterator's own {@code remove} or
jaroslav@597
    56
 * {@code add} methods, the iterator will throw a {@link
jaroslav@597
    57
 * ConcurrentModificationException}.  Thus, in the face of concurrent
jaroslav@597
    58
 * modification, the iterator fails quickly and cleanly, rather than
jaroslav@597
    59
 * risking arbitrary, non-deterministic behavior at an undetermined
jaroslav@597
    60
 * time in the future.
jaroslav@597
    61
 *
jaroslav@597
    62
 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
jaroslav@597
    63
 * as it is, generally speaking, impossible to make any hard guarantees in the
jaroslav@597
    64
 * presence of unsynchronized concurrent modification.  Fail-fast iterators
jaroslav@597
    65
 * throw {@code ConcurrentModificationException} on a best-effort basis.
jaroslav@597
    66
 * Therefore, it would be wrong to write a program that depended on this
jaroslav@597
    67
 * exception for its correctness:   <i>the fail-fast behavior of iterators
jaroslav@597
    68
 * should be used only to detect bugs.</i>
jaroslav@597
    69
 *
jaroslav@597
    70
 * <p>This class is a member of the
jaroslav@597
    71
 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
jaroslav@597
    72
 * Java Collections Framework</a>.
jaroslav@597
    73
 *
jaroslav@597
    74
 * @author  Josh Bloch
jaroslav@597
    75
 * @see     List
jaroslav@597
    76
 * @see     ArrayList
jaroslav@597
    77
 * @since 1.2
jaroslav@597
    78
 * @param <E> the type of elements held in this collection
jaroslav@597
    79
 */
jaroslav@597
    80
jaroslav@597
    81
public class LinkedList<E>
jaroslav@597
    82
    extends AbstractSequentialList<E>
jaroslav@597
    83
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
jaroslav@597
    84
{
jaroslav@597
    85
    transient int size = 0;
jaroslav@597
    86
jaroslav@597
    87
    /**
jaroslav@597
    88
     * Pointer to first node.
jaroslav@597
    89
     * Invariant: (first == null && last == null) ||
jaroslav@597
    90
     *            (first.prev == null && first.item != null)
jaroslav@597
    91
     */
jaroslav@597
    92
    transient Node<E> first;
jaroslav@597
    93
jaroslav@597
    94
    /**
jaroslav@597
    95
     * Pointer to last node.
jaroslav@597
    96
     * Invariant: (first == null && last == null) ||
jaroslav@597
    97
     *            (last.next == null && last.item != null)
jaroslav@597
    98
     */
jaroslav@597
    99
    transient Node<E> last;
jaroslav@597
   100
jaroslav@597
   101
    /**
jaroslav@597
   102
     * Constructs an empty list.
jaroslav@597
   103
     */
jaroslav@597
   104
    public LinkedList() {
jaroslav@597
   105
    }
jaroslav@597
   106
jaroslav@597
   107
    /**
jaroslav@597
   108
     * Constructs a list containing the elements of the specified
jaroslav@597
   109
     * collection, in the order they are returned by the collection's
jaroslav@597
   110
     * iterator.
jaroslav@597
   111
     *
jaroslav@597
   112
     * @param  c the collection whose elements are to be placed into this list
jaroslav@597
   113
     * @throws NullPointerException if the specified collection is null
jaroslav@597
   114
     */
jaroslav@597
   115
    public LinkedList(Collection<? extends E> c) {
jaroslav@597
   116
        this();
jaroslav@597
   117
        addAll(c);
jaroslav@597
   118
    }
jaroslav@597
   119
jaroslav@597
   120
    /**
jaroslav@597
   121
     * Links e as first element.
jaroslav@597
   122
     */
jaroslav@597
   123
    private void linkFirst(E e) {
jaroslav@597
   124
        final Node<E> f = first;
jaroslav@597
   125
        final Node<E> newNode = new Node<>(null, e, f);
jaroslav@597
   126
        first = newNode;
jaroslav@597
   127
        if (f == null)
jaroslav@597
   128
            last = newNode;
jaroslav@597
   129
        else
jaroslav@597
   130
            f.prev = newNode;
jaroslav@597
   131
        size++;
jaroslav@597
   132
        modCount++;
jaroslav@597
   133
    }
jaroslav@597
   134
jaroslav@597
   135
    /**
jaroslav@597
   136
     * Links e as last element.
jaroslav@597
   137
     */
jaroslav@597
   138
    void linkLast(E e) {
jaroslav@597
   139
        final Node<E> l = last;
jaroslav@597
   140
        final Node<E> newNode = new Node<>(l, e, null);
jaroslav@597
   141
        last = newNode;
jaroslav@597
   142
        if (l == null)
jaroslav@597
   143
            first = newNode;
jaroslav@597
   144
        else
jaroslav@597
   145
            l.next = newNode;
jaroslav@597
   146
        size++;
jaroslav@597
   147
        modCount++;
jaroslav@597
   148
    }
jaroslav@597
   149
jaroslav@597
   150
    /**
jaroslav@597
   151
     * Inserts element e before non-null Node succ.
jaroslav@597
   152
     */
jaroslav@597
   153
    void linkBefore(E e, Node<E> succ) {
jaroslav@597
   154
        // assert succ != null;
jaroslav@597
   155
        final Node<E> pred = succ.prev;
jaroslav@597
   156
        final Node<E> newNode = new Node<>(pred, e, succ);
jaroslav@597
   157
        succ.prev = newNode;
jaroslav@597
   158
        if (pred == null)
jaroslav@597
   159
            first = newNode;
jaroslav@597
   160
        else
jaroslav@597
   161
            pred.next = newNode;
jaroslav@597
   162
        size++;
jaroslav@597
   163
        modCount++;
jaroslav@597
   164
    }
jaroslav@597
   165
jaroslav@597
   166
    /**
jaroslav@597
   167
     * Unlinks non-null first node f.
jaroslav@597
   168
     */
jaroslav@597
   169
    private E unlinkFirst(Node<E> f) {
jaroslav@597
   170
        // assert f == first && f != null;
jaroslav@597
   171
        final E element = f.item;
jaroslav@597
   172
        final Node<E> next = f.next;
jaroslav@597
   173
        f.item = null;
jaroslav@597
   174
        f.next = null; // help GC
jaroslav@597
   175
        first = next;
jaroslav@597
   176
        if (next == null)
jaroslav@597
   177
            last = null;
jaroslav@597
   178
        else
jaroslav@597
   179
            next.prev = null;
jaroslav@597
   180
        size--;
jaroslav@597
   181
        modCount++;
jaroslav@597
   182
        return element;
jaroslav@597
   183
    }
jaroslav@597
   184
jaroslav@597
   185
    /**
jaroslav@597
   186
     * Unlinks non-null last node l.
jaroslav@597
   187
     */
jaroslav@597
   188
    private E unlinkLast(Node<E> l) {
jaroslav@597
   189
        // assert l == last && l != null;
jaroslav@597
   190
        final E element = l.item;
jaroslav@597
   191
        final Node<E> prev = l.prev;
jaroslav@597
   192
        l.item = null;
jaroslav@597
   193
        l.prev = null; // help GC
jaroslav@597
   194
        last = prev;
jaroslav@597
   195
        if (prev == null)
jaroslav@597
   196
            first = null;
jaroslav@597
   197
        else
jaroslav@597
   198
            prev.next = null;
jaroslav@597
   199
        size--;
jaroslav@597
   200
        modCount++;
jaroslav@597
   201
        return element;
jaroslav@597
   202
    }
jaroslav@597
   203
jaroslav@597
   204
    /**
jaroslav@597
   205
     * Unlinks non-null node x.
jaroslav@597
   206
     */
jaroslav@597
   207
    E unlink(Node<E> x) {
jaroslav@597
   208
        // assert x != null;
jaroslav@597
   209
        final E element = x.item;
jaroslav@597
   210
        final Node<E> next = x.next;
jaroslav@597
   211
        final Node<E> prev = x.prev;
jaroslav@597
   212
jaroslav@597
   213
        if (prev == null) {
jaroslav@597
   214
            first = next;
jaroslav@597
   215
        } else {
jaroslav@597
   216
            prev.next = next;
jaroslav@597
   217
            x.prev = null;
jaroslav@597
   218
        }
jaroslav@597
   219
jaroslav@597
   220
        if (next == null) {
jaroslav@597
   221
            last = prev;
jaroslav@597
   222
        } else {
jaroslav@597
   223
            next.prev = prev;
jaroslav@597
   224
            x.next = null;
jaroslav@597
   225
        }
jaroslav@597
   226
jaroslav@597
   227
        x.item = null;
jaroslav@597
   228
        size--;
jaroslav@597
   229
        modCount++;
jaroslav@597
   230
        return element;
jaroslav@597
   231
    }
jaroslav@597
   232
jaroslav@597
   233
    /**
jaroslav@597
   234
     * Returns the first element in this list.
jaroslav@597
   235
     *
jaroslav@597
   236
     * @return the first element in this list
jaroslav@597
   237
     * @throws NoSuchElementException if this list is empty
jaroslav@597
   238
     */
jaroslav@597
   239
    public E getFirst() {
jaroslav@597
   240
        final Node<E> f = first;
jaroslav@597
   241
        if (f == null)
jaroslav@597
   242
            throw new NoSuchElementException();
jaroslav@597
   243
        return f.item;
jaroslav@597
   244
    }
jaroslav@597
   245
jaroslav@597
   246
    /**
jaroslav@597
   247
     * Returns the last element in this list.
jaroslav@597
   248
     *
jaroslav@597
   249
     * @return the last element in this list
jaroslav@597
   250
     * @throws NoSuchElementException if this list is empty
jaroslav@597
   251
     */
jaroslav@597
   252
    public E getLast() {
jaroslav@597
   253
        final Node<E> l = last;
jaroslav@597
   254
        if (l == null)
jaroslav@597
   255
            throw new NoSuchElementException();
jaroslav@597
   256
        return l.item;
jaroslav@597
   257
    }
jaroslav@597
   258
jaroslav@597
   259
    /**
jaroslav@597
   260
     * Removes and returns the first element from this list.
jaroslav@597
   261
     *
jaroslav@597
   262
     * @return the first element from this list
jaroslav@597
   263
     * @throws NoSuchElementException if this list is empty
jaroslav@597
   264
     */
jaroslav@597
   265
    public E removeFirst() {
jaroslav@597
   266
        final Node<E> f = first;
jaroslav@597
   267
        if (f == null)
jaroslav@597
   268
            throw new NoSuchElementException();
jaroslav@597
   269
        return unlinkFirst(f);
jaroslav@597
   270
    }
jaroslav@597
   271
jaroslav@597
   272
    /**
jaroslav@597
   273
     * Removes and returns the last element from this list.
jaroslav@597
   274
     *
jaroslav@597
   275
     * @return the last element from this list
jaroslav@597
   276
     * @throws NoSuchElementException if this list is empty
jaroslav@597
   277
     */
jaroslav@597
   278
    public E removeLast() {
jaroslav@597
   279
        final Node<E> l = last;
jaroslav@597
   280
        if (l == null)
jaroslav@597
   281
            throw new NoSuchElementException();
jaroslav@597
   282
        return unlinkLast(l);
jaroslav@597
   283
    }
jaroslav@597
   284
jaroslav@597
   285
    /**
jaroslav@597
   286
     * Inserts the specified element at the beginning of this list.
jaroslav@597
   287
     *
jaroslav@597
   288
     * @param e the element to add
jaroslav@597
   289
     */
jaroslav@597
   290
    public void addFirst(E e) {
jaroslav@597
   291
        linkFirst(e);
jaroslav@597
   292
    }
jaroslav@597
   293
jaroslav@597
   294
    /**
jaroslav@597
   295
     * Appends the specified element to the end of this list.
jaroslav@597
   296
     *
jaroslav@597
   297
     * <p>This method is equivalent to {@link #add}.
jaroslav@597
   298
     *
jaroslav@597
   299
     * @param e the element to add
jaroslav@597
   300
     */
jaroslav@597
   301
    public void addLast(E e) {
jaroslav@597
   302
        linkLast(e);
jaroslav@597
   303
    }
jaroslav@597
   304
jaroslav@597
   305
    /**
jaroslav@597
   306
     * Returns {@code true} if this list contains the specified element.
jaroslav@597
   307
     * More formally, returns {@code true} if and only if this list contains
jaroslav@597
   308
     * at least one element {@code e} such that
jaroslav@597
   309
     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
jaroslav@597
   310
     *
jaroslav@597
   311
     * @param o element whose presence in this list is to be tested
jaroslav@597
   312
     * @return {@code true} if this list contains the specified element
jaroslav@597
   313
     */
jaroslav@597
   314
    public boolean contains(Object o) {
jaroslav@597
   315
        return indexOf(o) != -1;
jaroslav@597
   316
    }
jaroslav@597
   317
jaroslav@597
   318
    /**
jaroslav@597
   319
     * Returns the number of elements in this list.
jaroslav@597
   320
     *
jaroslav@597
   321
     * @return the number of elements in this list
jaroslav@597
   322
     */
jaroslav@597
   323
    public int size() {
jaroslav@597
   324
        return size;
jaroslav@597
   325
    }
jaroslav@597
   326
jaroslav@597
   327
    /**
jaroslav@597
   328
     * Appends the specified element to the end of this list.
jaroslav@597
   329
     *
jaroslav@597
   330
     * <p>This method is equivalent to {@link #addLast}.
jaroslav@597
   331
     *
jaroslav@597
   332
     * @param e element to be appended to this list
jaroslav@597
   333
     * @return {@code true} (as specified by {@link Collection#add})
jaroslav@597
   334
     */
jaroslav@597
   335
    public boolean add(E e) {
jaroslav@597
   336
        linkLast(e);
jaroslav@597
   337
        return true;
jaroslav@597
   338
    }
jaroslav@597
   339
jaroslav@597
   340
    /**
jaroslav@597
   341
     * Removes the first occurrence of the specified element from this list,
jaroslav@597
   342
     * if it is present.  If this list does not contain the element, it is
jaroslav@597
   343
     * unchanged.  More formally, removes the element with the lowest index
jaroslav@597
   344
     * {@code i} such that
jaroslav@597
   345
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
jaroslav@597
   346
     * (if such an element exists).  Returns {@code true} if this list
jaroslav@597
   347
     * contained the specified element (or equivalently, if this list
jaroslav@597
   348
     * changed as a result of the call).
jaroslav@597
   349
     *
jaroslav@597
   350
     * @param o element to be removed from this list, if present
jaroslav@597
   351
     * @return {@code true} if this list contained the specified element
jaroslav@597
   352
     */
jaroslav@597
   353
    public boolean remove(Object o) {
jaroslav@597
   354
        if (o == null) {
jaroslav@597
   355
            for (Node<E> x = first; x != null; x = x.next) {
jaroslav@597
   356
                if (x.item == null) {
jaroslav@597
   357
                    unlink(x);
jaroslav@597
   358
                    return true;
jaroslav@597
   359
                }
jaroslav@597
   360
            }
jaroslav@597
   361
        } else {
jaroslav@597
   362
            for (Node<E> x = first; x != null; x = x.next) {
jaroslav@597
   363
                if (o.equals(x.item)) {
jaroslav@597
   364
                    unlink(x);
jaroslav@597
   365
                    return true;
jaroslav@597
   366
                }
jaroslav@597
   367
            }
jaroslav@597
   368
        }
jaroslav@597
   369
        return false;
jaroslav@597
   370
    }
jaroslav@597
   371
jaroslav@597
   372
    /**
jaroslav@597
   373
     * Appends all of the elements in the specified collection to the end of
jaroslav@597
   374
     * this list, in the order that they are returned by the specified
jaroslav@597
   375
     * collection's iterator.  The behavior of this operation is undefined if
jaroslav@597
   376
     * the specified collection is modified while the operation is in
jaroslav@597
   377
     * progress.  (Note that this will occur if the specified collection is
jaroslav@597
   378
     * this list, and it's nonempty.)
jaroslav@597
   379
     *
jaroslav@597
   380
     * @param c collection containing elements to be added to this list
jaroslav@597
   381
     * @return {@code true} if this list changed as a result of the call
jaroslav@597
   382
     * @throws NullPointerException if the specified collection is null
jaroslav@597
   383
     */
jaroslav@597
   384
    public boolean addAll(Collection<? extends E> c) {
jaroslav@597
   385
        return addAll(size, c);
jaroslav@597
   386
    }
jaroslav@597
   387
jaroslav@597
   388
    /**
jaroslav@597
   389
     * Inserts all of the elements in the specified collection into this
jaroslav@597
   390
     * list, starting at the specified position.  Shifts the element
jaroslav@597
   391
     * currently at that position (if any) and any subsequent elements to
jaroslav@597
   392
     * the right (increases their indices).  The new elements will appear
jaroslav@597
   393
     * in the list in the order that they are returned by the
jaroslav@597
   394
     * specified collection's iterator.
jaroslav@597
   395
     *
jaroslav@597
   396
     * @param index index at which to insert the first element
jaroslav@597
   397
     *              from the specified collection
jaroslav@597
   398
     * @param c collection containing elements to be added to this list
jaroslav@597
   399
     * @return {@code true} if this list changed as a result of the call
jaroslav@597
   400
     * @throws IndexOutOfBoundsException {@inheritDoc}
jaroslav@597
   401
     * @throws NullPointerException if the specified collection is null
jaroslav@597
   402
     */
jaroslav@597
   403
    public boolean addAll(int index, Collection<? extends E> c) {
jaroslav@597
   404
        checkPositionIndex(index);
jaroslav@597
   405
jaroslav@597
   406
        Object[] a = c.toArray();
jaroslav@597
   407
        int numNew = a.length;
jaroslav@597
   408
        if (numNew == 0)
jaroslav@597
   409
            return false;
jaroslav@597
   410
jaroslav@597
   411
        Node<E> pred, succ;
jaroslav@597
   412
        if (index == size) {
jaroslav@597
   413
            succ = null;
jaroslav@597
   414
            pred = last;
jaroslav@597
   415
        } else {
jaroslav@597
   416
            succ = node(index);
jaroslav@597
   417
            pred = succ.prev;
jaroslav@597
   418
        }
jaroslav@597
   419
jaroslav@597
   420
        for (Object o : a) {
jaroslav@597
   421
            @SuppressWarnings("unchecked") E e = (E) o;
jaroslav@597
   422
            Node<E> newNode = new Node<>(pred, e, null);
jaroslav@597
   423
            if (pred == null)
jaroslav@597
   424
                first = newNode;
jaroslav@597
   425
            else
jaroslav@597
   426
                pred.next = newNode;
jaroslav@597
   427
            pred = newNode;
jaroslav@597
   428
        }
jaroslav@597
   429
jaroslav@597
   430
        if (succ == null) {
jaroslav@597
   431
            last = pred;
jaroslav@597
   432
        } else {
jaroslav@597
   433
            pred.next = succ;
jaroslav@597
   434
            succ.prev = pred;
jaroslav@597
   435
        }
jaroslav@597
   436
jaroslav@597
   437
        size += numNew;
jaroslav@597
   438
        modCount++;
jaroslav@597
   439
        return true;
jaroslav@597
   440
    }
jaroslav@597
   441
jaroslav@597
   442
    /**
jaroslav@597
   443
     * Removes all of the elements from this list.
jaroslav@597
   444
     * The list will be empty after this call returns.
jaroslav@597
   445
     */
jaroslav@597
   446
    public void clear() {
jaroslav@597
   447
        // Clearing all of the links between nodes is "unnecessary", but:
jaroslav@597
   448
        // - helps a generational GC if the discarded nodes inhabit
jaroslav@597
   449
        //   more than one generation
jaroslav@597
   450
        // - is sure to free memory even if there is a reachable Iterator
jaroslav@597
   451
        for (Node<E> x = first; x != null; ) {
jaroslav@597
   452
            Node<E> next = x.next;
jaroslav@597
   453
            x.item = null;
jaroslav@597
   454
            x.next = null;
jaroslav@597
   455
            x.prev = null;
jaroslav@597
   456
            x = next;
jaroslav@597
   457
        }
jaroslav@597
   458
        first = last = null;
jaroslav@597
   459
        size = 0;
jaroslav@597
   460
        modCount++;
jaroslav@597
   461
    }
jaroslav@597
   462
jaroslav@597
   463
jaroslav@597
   464
    // Positional Access Operations
jaroslav@597
   465
jaroslav@597
   466
    /**
jaroslav@597
   467
     * Returns the element at the specified position in this list.
jaroslav@597
   468
     *
jaroslav@597
   469
     * @param index index of the element to return
jaroslav@597
   470
     * @return the element at the specified position in this list
jaroslav@597
   471
     * @throws IndexOutOfBoundsException {@inheritDoc}
jaroslav@597
   472
     */
jaroslav@597
   473
    public E get(int index) {
jaroslav@597
   474
        checkElementIndex(index);
jaroslav@597
   475
        return node(index).item;
jaroslav@597
   476
    }
jaroslav@597
   477
jaroslav@597
   478
    /**
jaroslav@597
   479
     * Replaces the element at the specified position in this list with the
jaroslav@597
   480
     * specified element.
jaroslav@597
   481
     *
jaroslav@597
   482
     * @param index index of the element to replace
jaroslav@597
   483
     * @param element element to be stored at the specified position
jaroslav@597
   484
     * @return the element previously at the specified position
jaroslav@597
   485
     * @throws IndexOutOfBoundsException {@inheritDoc}
jaroslav@597
   486
     */
jaroslav@597
   487
    public E set(int index, E element) {
jaroslav@597
   488
        checkElementIndex(index);
jaroslav@597
   489
        Node<E> x = node(index);
jaroslav@597
   490
        E oldVal = x.item;
jaroslav@597
   491
        x.item = element;
jaroslav@597
   492
        return oldVal;
jaroslav@597
   493
    }
jaroslav@597
   494
jaroslav@597
   495
    /**
jaroslav@597
   496
     * Inserts the specified element at the specified position in this list.
jaroslav@597
   497
     * Shifts the element currently at that position (if any) and any
jaroslav@597
   498
     * subsequent elements to the right (adds one to their indices).
jaroslav@597
   499
     *
jaroslav@597
   500
     * @param index index at which the specified element is to be inserted
jaroslav@597
   501
     * @param element element to be inserted
jaroslav@597
   502
     * @throws IndexOutOfBoundsException {@inheritDoc}
jaroslav@597
   503
     */
jaroslav@597
   504
    public void add(int index, E element) {
jaroslav@597
   505
        checkPositionIndex(index);
jaroslav@597
   506
jaroslav@597
   507
        if (index == size)
jaroslav@597
   508
            linkLast(element);
jaroslav@597
   509
        else
jaroslav@597
   510
            linkBefore(element, node(index));
jaroslav@597
   511
    }
jaroslav@597
   512
jaroslav@597
   513
    /**
jaroslav@597
   514
     * Removes the element at the specified position in this list.  Shifts any
jaroslav@597
   515
     * subsequent elements to the left (subtracts one from their indices).
jaroslav@597
   516
     * Returns the element that was removed from the list.
jaroslav@597
   517
     *
jaroslav@597
   518
     * @param index the index of the element to be removed
jaroslav@597
   519
     * @return the element previously at the specified position
jaroslav@597
   520
     * @throws IndexOutOfBoundsException {@inheritDoc}
jaroslav@597
   521
     */
jaroslav@597
   522
    public E remove(int index) {
jaroslav@597
   523
        checkElementIndex(index);
jaroslav@597
   524
        return unlink(node(index));
jaroslav@597
   525
    }
jaroslav@597
   526
jaroslav@597
   527
    /**
jaroslav@597
   528
     * Tells if the argument is the index of an existing element.
jaroslav@597
   529
     */
jaroslav@597
   530
    private boolean isElementIndex(int index) {
jaroslav@597
   531
        return index >= 0 && index < size;
jaroslav@597
   532
    }
jaroslav@597
   533
jaroslav@597
   534
    /**
jaroslav@597
   535
     * Tells if the argument is the index of a valid position for an
jaroslav@597
   536
     * iterator or an add operation.
jaroslav@597
   537
     */
jaroslav@597
   538
    private boolean isPositionIndex(int index) {
jaroslav@597
   539
        return index >= 0 && index <= size;
jaroslav@597
   540
    }
jaroslav@597
   541
jaroslav@597
   542
    /**
jaroslav@597
   543
     * Constructs an IndexOutOfBoundsException detail message.
jaroslav@597
   544
     * Of the many possible refactorings of the error handling code,
jaroslav@597
   545
     * this "outlining" performs best with both server and client VMs.
jaroslav@597
   546
     */
jaroslav@597
   547
    private String outOfBoundsMsg(int index) {
jaroslav@597
   548
        return "Index: "+index+", Size: "+size;
jaroslav@597
   549
    }
jaroslav@597
   550
jaroslav@597
   551
    private void checkElementIndex(int index) {
jaroslav@597
   552
        if (!isElementIndex(index))
jaroslav@597
   553
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
jaroslav@597
   554
    }
jaroslav@597
   555
jaroslav@597
   556
    private void checkPositionIndex(int index) {
jaroslav@597
   557
        if (!isPositionIndex(index))
jaroslav@597
   558
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
jaroslav@597
   559
    }
jaroslav@597
   560
jaroslav@597
   561
    /**
jaroslav@597
   562
     * Returns the (non-null) Node at the specified element index.
jaroslav@597
   563
     */
jaroslav@597
   564
    Node<E> node(int index) {
jaroslav@597
   565
        // assert isElementIndex(index);
jaroslav@597
   566
jaroslav@597
   567
        if (index < (size >> 1)) {
jaroslav@597
   568
            Node<E> x = first;
jaroslav@597
   569
            for (int i = 0; i < index; i++)
jaroslav@597
   570
                x = x.next;
jaroslav@597
   571
            return x;
jaroslav@597
   572
        } else {
jaroslav@597
   573
            Node<E> x = last;
jaroslav@597
   574
            for (int i = size - 1; i > index; i--)
jaroslav@597
   575
                x = x.prev;
jaroslav@597
   576
            return x;
jaroslav@597
   577
        }
jaroslav@597
   578
    }
jaroslav@597
   579
jaroslav@597
   580
    // Search Operations
jaroslav@597
   581
jaroslav@597
   582
    /**
jaroslav@597
   583
     * Returns the index of the first occurrence of the specified element
jaroslav@597
   584
     * in this list, or -1 if this list does not contain the element.
jaroslav@597
   585
     * More formally, returns the lowest index {@code i} such that
jaroslav@597
   586
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
jaroslav@597
   587
     * or -1 if there is no such index.
jaroslav@597
   588
     *
jaroslav@597
   589
     * @param o element to search for
jaroslav@597
   590
     * @return the index of the first occurrence of the specified element in
jaroslav@597
   591
     *         this list, or -1 if this list does not contain the element
jaroslav@597
   592
     */
jaroslav@597
   593
    public int indexOf(Object o) {
jaroslav@597
   594
        int index = 0;
jaroslav@597
   595
        if (o == null) {
jaroslav@597
   596
            for (Node<E> x = first; x != null; x = x.next) {
jaroslav@597
   597
                if (x.item == null)
jaroslav@597
   598
                    return index;
jaroslav@597
   599
                index++;
jaroslav@597
   600
            }
jaroslav@597
   601
        } else {
jaroslav@597
   602
            for (Node<E> x = first; x != null; x = x.next) {
jaroslav@597
   603
                if (o.equals(x.item))
jaroslav@597
   604
                    return index;
jaroslav@597
   605
                index++;
jaroslav@597
   606
            }
jaroslav@597
   607
        }
jaroslav@597
   608
        return -1;
jaroslav@597
   609
    }
jaroslav@597
   610
jaroslav@597
   611
    /**
jaroslav@597
   612
     * Returns the index of the last occurrence of the specified element
jaroslav@597
   613
     * in this list, or -1 if this list does not contain the element.
jaroslav@597
   614
     * More formally, returns the highest index {@code i} such that
jaroslav@597
   615
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
jaroslav@597
   616
     * or -1 if there is no such index.
jaroslav@597
   617
     *
jaroslav@597
   618
     * @param o element to search for
jaroslav@597
   619
     * @return the index of the last occurrence of the specified element in
jaroslav@597
   620
     *         this list, or -1 if this list does not contain the element
jaroslav@597
   621
     */
jaroslav@597
   622
    public int lastIndexOf(Object o) {
jaroslav@597
   623
        int index = size;
jaroslav@597
   624
        if (o == null) {
jaroslav@597
   625
            for (Node<E> x = last; x != null; x = x.prev) {
jaroslav@597
   626
                index--;
jaroslav@597
   627
                if (x.item == null)
jaroslav@597
   628
                    return index;
jaroslav@597
   629
            }
jaroslav@597
   630
        } else {
jaroslav@597
   631
            for (Node<E> x = last; x != null; x = x.prev) {
jaroslav@597
   632
                index--;
jaroslav@597
   633
                if (o.equals(x.item))
jaroslav@597
   634
                    return index;
jaroslav@597
   635
            }
jaroslav@597
   636
        }
jaroslav@597
   637
        return -1;
jaroslav@597
   638
    }
jaroslav@597
   639
jaroslav@597
   640
    // Queue operations.
jaroslav@597
   641
jaroslav@597
   642
    /**
jaroslav@597
   643
     * Retrieves, but does not remove, the head (first element) of this list.
jaroslav@597
   644
     *
jaroslav@597
   645
     * @return the head of this list, or {@code null} if this list is empty
jaroslav@597
   646
     * @since 1.5
jaroslav@597
   647
     */
jaroslav@597
   648
    public E peek() {
jaroslav@597
   649
        final Node<E> f = first;
jaroslav@597
   650
        return (f == null) ? null : f.item;
jaroslav@597
   651
    }
jaroslav@597
   652
jaroslav@597
   653
    /**
jaroslav@597
   654
     * Retrieves, but does not remove, the head (first element) of this list.
jaroslav@597
   655
     *
jaroslav@597
   656
     * @return the head of this list
jaroslav@597
   657
     * @throws NoSuchElementException if this list is empty
jaroslav@597
   658
     * @since 1.5
jaroslav@597
   659
     */
jaroslav@597
   660
    public E element() {
jaroslav@597
   661
        return getFirst();
jaroslav@597
   662
    }
jaroslav@597
   663
jaroslav@597
   664
    /**
jaroslav@597
   665
     * Retrieves and removes the head (first element) of this list.
jaroslav@597
   666
     *
jaroslav@597
   667
     * @return the head of this list, or {@code null} if this list is empty
jaroslav@597
   668
     * @since 1.5
jaroslav@597
   669
     */
jaroslav@597
   670
    public E poll() {
jaroslav@597
   671
        final Node<E> f = first;
jaroslav@597
   672
        return (f == null) ? null : unlinkFirst(f);
jaroslav@597
   673
    }
jaroslav@597
   674
jaroslav@597
   675
    /**
jaroslav@597
   676
     * Retrieves and removes the head (first element) of this list.
jaroslav@597
   677
     *
jaroslav@597
   678
     * @return the head of this list
jaroslav@597
   679
     * @throws NoSuchElementException if this list is empty
jaroslav@597
   680
     * @since 1.5
jaroslav@597
   681
     */
jaroslav@597
   682
    public E remove() {
jaroslav@597
   683
        return removeFirst();
jaroslav@597
   684
    }
jaroslav@597
   685
jaroslav@597
   686
    /**
jaroslav@597
   687
     * Adds the specified element as the tail (last element) of this list.
jaroslav@597
   688
     *
jaroslav@597
   689
     * @param e the element to add
jaroslav@597
   690
     * @return {@code true} (as specified by {@link Queue#offer})
jaroslav@597
   691
     * @since 1.5
jaroslav@597
   692
     */
jaroslav@597
   693
    public boolean offer(E e) {
jaroslav@597
   694
        return add(e);
jaroslav@597
   695
    }
jaroslav@597
   696
jaroslav@597
   697
    // Deque operations
jaroslav@597
   698
    /**
jaroslav@597
   699
     * Inserts the specified element at the front of this list.
jaroslav@597
   700
     *
jaroslav@597
   701
     * @param e the element to insert
jaroslav@597
   702
     * @return {@code true} (as specified by {@link Deque#offerFirst})
jaroslav@597
   703
     * @since 1.6
jaroslav@597
   704
     */
jaroslav@597
   705
    public boolean offerFirst(E e) {
jaroslav@597
   706
        addFirst(e);
jaroslav@597
   707
        return true;
jaroslav@597
   708
    }
jaroslav@597
   709
jaroslav@597
   710
    /**
jaroslav@597
   711
     * Inserts the specified element at the end of this list.
jaroslav@597
   712
     *
jaroslav@597
   713
     * @param e the element to insert
jaroslav@597
   714
     * @return {@code true} (as specified by {@link Deque#offerLast})
jaroslav@597
   715
     * @since 1.6
jaroslav@597
   716
     */
jaroslav@597
   717
    public boolean offerLast(E e) {
jaroslav@597
   718
        addLast(e);
jaroslav@597
   719
        return true;
jaroslav@597
   720
    }
jaroslav@597
   721
jaroslav@597
   722
    /**
jaroslav@597
   723
     * Retrieves, but does not remove, the first element of this list,
jaroslav@597
   724
     * or returns {@code null} if this list is empty.
jaroslav@597
   725
     *
jaroslav@597
   726
     * @return the first element of this list, or {@code null}
jaroslav@597
   727
     *         if this list is empty
jaroslav@597
   728
     * @since 1.6
jaroslav@597
   729
     */
jaroslav@597
   730
    public E peekFirst() {
jaroslav@597
   731
        final Node<E> f = first;
jaroslav@597
   732
        return (f == null) ? null : f.item;
jaroslav@597
   733
     }
jaroslav@597
   734
jaroslav@597
   735
    /**
jaroslav@597
   736
     * Retrieves, but does not remove, the last element of this list,
jaroslav@597
   737
     * or returns {@code null} if this list is empty.
jaroslav@597
   738
     *
jaroslav@597
   739
     * @return the last element of this list, or {@code null}
jaroslav@597
   740
     *         if this list is empty
jaroslav@597
   741
     * @since 1.6
jaroslav@597
   742
     */
jaroslav@597
   743
    public E peekLast() {
jaroslav@597
   744
        final Node<E> l = last;
jaroslav@597
   745
        return (l == null) ? null : l.item;
jaroslav@597
   746
    }
jaroslav@597
   747
jaroslav@597
   748
    /**
jaroslav@597
   749
     * Retrieves and removes the first element of this list,
jaroslav@597
   750
     * or returns {@code null} if this list is empty.
jaroslav@597
   751
     *
jaroslav@597
   752
     * @return the first element of this list, or {@code null} if
jaroslav@597
   753
     *     this list is empty
jaroslav@597
   754
     * @since 1.6
jaroslav@597
   755
     */
jaroslav@597
   756
    public E pollFirst() {
jaroslav@597
   757
        final Node<E> f = first;
jaroslav@597
   758
        return (f == null) ? null : unlinkFirst(f);
jaroslav@597
   759
    }
jaroslav@597
   760
jaroslav@597
   761
    /**
jaroslav@597
   762
     * Retrieves and removes the last element of this list,
jaroslav@597
   763
     * or returns {@code null} if this list is empty.
jaroslav@597
   764
     *
jaroslav@597
   765
     * @return the last element of this list, or {@code null} if
jaroslav@597
   766
     *     this list is empty
jaroslav@597
   767
     * @since 1.6
jaroslav@597
   768
     */
jaroslav@597
   769
    public E pollLast() {
jaroslav@597
   770
        final Node<E> l = last;
jaroslav@597
   771
        return (l == null) ? null : unlinkLast(l);
jaroslav@597
   772
    }
jaroslav@597
   773
jaroslav@597
   774
    /**
jaroslav@597
   775
     * Pushes an element onto the stack represented by this list.  In other
jaroslav@597
   776
     * words, inserts the element at the front of this list.
jaroslav@597
   777
     *
jaroslav@597
   778
     * <p>This method is equivalent to {@link #addFirst}.
jaroslav@597
   779
     *
jaroslav@597
   780
     * @param e the element to push
jaroslav@597
   781
     * @since 1.6
jaroslav@597
   782
     */
jaroslav@597
   783
    public void push(E e) {
jaroslav@597
   784
        addFirst(e);
jaroslav@597
   785
    }
jaroslav@597
   786
jaroslav@597
   787
    /**
jaroslav@597
   788
     * Pops an element from the stack represented by this list.  In other
jaroslav@597
   789
     * words, removes and returns the first element of this list.
jaroslav@597
   790
     *
jaroslav@597
   791
     * <p>This method is equivalent to {@link #removeFirst()}.
jaroslav@597
   792
     *
jaroslav@597
   793
     * @return the element at the front of this list (which is the top
jaroslav@597
   794
     *         of the stack represented by this list)
jaroslav@597
   795
     * @throws NoSuchElementException if this list is empty
jaroslav@597
   796
     * @since 1.6
jaroslav@597
   797
     */
jaroslav@597
   798
    public E pop() {
jaroslav@597
   799
        return removeFirst();
jaroslav@597
   800
    }
jaroslav@597
   801
jaroslav@597
   802
    /**
jaroslav@597
   803
     * Removes the first occurrence of the specified element in this
jaroslav@597
   804
     * list (when traversing the list from head to tail).  If the list
jaroslav@597
   805
     * does not contain the element, it is unchanged.
jaroslav@597
   806
     *
jaroslav@597
   807
     * @param o element to be removed from this list, if present
jaroslav@597
   808
     * @return {@code true} if the list contained the specified element
jaroslav@597
   809
     * @since 1.6
jaroslav@597
   810
     */
jaroslav@597
   811
    public boolean removeFirstOccurrence(Object o) {
jaroslav@597
   812
        return remove(o);
jaroslav@597
   813
    }
jaroslav@597
   814
jaroslav@597
   815
    /**
jaroslav@597
   816
     * Removes the last occurrence of the specified element in this
jaroslav@597
   817
     * list (when traversing the list from head to tail).  If the list
jaroslav@597
   818
     * does not contain the element, it is unchanged.
jaroslav@597
   819
     *
jaroslav@597
   820
     * @param o element to be removed from this list, if present
jaroslav@597
   821
     * @return {@code true} if the list contained the specified element
jaroslav@597
   822
     * @since 1.6
jaroslav@597
   823
     */
jaroslav@597
   824
    public boolean removeLastOccurrence(Object o) {
jaroslav@597
   825
        if (o == null) {
jaroslav@597
   826
            for (Node<E> x = last; x != null; x = x.prev) {
jaroslav@597
   827
                if (x.item == null) {
jaroslav@597
   828
                    unlink(x);
jaroslav@597
   829
                    return true;
jaroslav@597
   830
                }
jaroslav@597
   831
            }
jaroslav@597
   832
        } else {
jaroslav@597
   833
            for (Node<E> x = last; x != null; x = x.prev) {
jaroslav@597
   834
                if (o.equals(x.item)) {
jaroslav@597
   835
                    unlink(x);
jaroslav@597
   836
                    return true;
jaroslav@597
   837
                }
jaroslav@597
   838
            }
jaroslav@597
   839
        }
jaroslav@597
   840
        return false;
jaroslav@597
   841
    }
jaroslav@597
   842
jaroslav@597
   843
    /**
jaroslav@597
   844
     * Returns a list-iterator of the elements in this list (in proper
jaroslav@597
   845
     * sequence), starting at the specified position in the list.
jaroslav@597
   846
     * Obeys the general contract of {@code List.listIterator(int)}.<p>
jaroslav@597
   847
     *
jaroslav@597
   848
     * The list-iterator is <i>fail-fast</i>: if the list is structurally
jaroslav@597
   849
     * modified at any time after the Iterator is created, in any way except
jaroslav@597
   850
     * through the list-iterator's own {@code remove} or {@code add}
jaroslav@597
   851
     * methods, the list-iterator will throw a
jaroslav@597
   852
     * {@code ConcurrentModificationException}.  Thus, in the face of
jaroslav@597
   853
     * concurrent modification, the iterator fails quickly and cleanly, rather
jaroslav@597
   854
     * than risking arbitrary, non-deterministic behavior at an undetermined
jaroslav@597
   855
     * time in the future.
jaroslav@597
   856
     *
jaroslav@597
   857
     * @param index index of the first element to be returned from the
jaroslav@597
   858
     *              list-iterator (by a call to {@code next})
jaroslav@597
   859
     * @return a ListIterator of the elements in this list (in proper
jaroslav@597
   860
     *         sequence), starting at the specified position in the list
jaroslav@597
   861
     * @throws IndexOutOfBoundsException {@inheritDoc}
jaroslav@597
   862
     * @see List#listIterator(int)
jaroslav@597
   863
     */
jaroslav@597
   864
    public ListIterator<E> listIterator(int index) {
jaroslav@597
   865
        checkPositionIndex(index);
jaroslav@597
   866
        return new ListItr(index);
jaroslav@597
   867
    }
jaroslav@597
   868
jaroslav@597
   869
    private class ListItr implements ListIterator<E> {
jaroslav@597
   870
        private Node<E> lastReturned = null;
jaroslav@597
   871
        private Node<E> next;
jaroslav@597
   872
        private int nextIndex;
jaroslav@597
   873
        private int expectedModCount = modCount;
jaroslav@597
   874
jaroslav@597
   875
        ListItr(int index) {
jaroslav@597
   876
            // assert isPositionIndex(index);
jaroslav@597
   877
            next = (index == size) ? null : node(index);
jaroslav@597
   878
            nextIndex = index;
jaroslav@597
   879
        }
jaroslav@597
   880
jaroslav@597
   881
        public boolean hasNext() {
jaroslav@597
   882
            return nextIndex < size;
jaroslav@597
   883
        }
jaroslav@597
   884
jaroslav@597
   885
        public E next() {
jaroslav@597
   886
            checkForComodification();
jaroslav@597
   887
            if (!hasNext())
jaroslav@597
   888
                throw new NoSuchElementException();
jaroslav@597
   889
jaroslav@597
   890
            lastReturned = next;
jaroslav@597
   891
            next = next.next;
jaroslav@597
   892
            nextIndex++;
jaroslav@597
   893
            return lastReturned.item;
jaroslav@597
   894
        }
jaroslav@597
   895
jaroslav@597
   896
        public boolean hasPrevious() {
jaroslav@597
   897
            return nextIndex > 0;
jaroslav@597
   898
        }
jaroslav@597
   899
jaroslav@597
   900
        public E previous() {
jaroslav@597
   901
            checkForComodification();
jaroslav@597
   902
            if (!hasPrevious())
jaroslav@597
   903
                throw new NoSuchElementException();
jaroslav@597
   904
jaroslav@597
   905
            lastReturned = next = (next == null) ? last : next.prev;
jaroslav@597
   906
            nextIndex--;
jaroslav@597
   907
            return lastReturned.item;
jaroslav@597
   908
        }
jaroslav@597
   909
jaroslav@597
   910
        public int nextIndex() {
jaroslav@597
   911
            return nextIndex;
jaroslav@597
   912
        }
jaroslav@597
   913
jaroslav@597
   914
        public int previousIndex() {
jaroslav@597
   915
            return nextIndex - 1;
jaroslav@597
   916
        }
jaroslav@597
   917
jaroslav@597
   918
        public void remove() {
jaroslav@597
   919
            checkForComodification();
jaroslav@597
   920
            if (lastReturned == null)
jaroslav@597
   921
                throw new IllegalStateException();
jaroslav@597
   922
jaroslav@597
   923
            Node<E> lastNext = lastReturned.next;
jaroslav@597
   924
            unlink(lastReturned);
jaroslav@597
   925
            if (next == lastReturned)
jaroslav@597
   926
                next = lastNext;
jaroslav@597
   927
            else
jaroslav@597
   928
                nextIndex--;
jaroslav@597
   929
            lastReturned = null;
jaroslav@597
   930
            expectedModCount++;
jaroslav@597
   931
        }
jaroslav@597
   932
jaroslav@597
   933
        public void set(E e) {
jaroslav@597
   934
            if (lastReturned == null)
jaroslav@597
   935
                throw new IllegalStateException();
jaroslav@597
   936
            checkForComodification();
jaroslav@597
   937
            lastReturned.item = e;
jaroslav@597
   938
        }
jaroslav@597
   939
jaroslav@597
   940
        public void add(E e) {
jaroslav@597
   941
            checkForComodification();
jaroslav@597
   942
            lastReturned = null;
jaroslav@597
   943
            if (next == null)
jaroslav@597
   944
                linkLast(e);
jaroslav@597
   945
            else
jaroslav@597
   946
                linkBefore(e, next);
jaroslav@597
   947
            nextIndex++;
jaroslav@597
   948
            expectedModCount++;
jaroslav@597
   949
        }
jaroslav@597
   950
jaroslav@597
   951
        final void checkForComodification() {
jaroslav@597
   952
            if (modCount != expectedModCount)
jaroslav@597
   953
                throw new ConcurrentModificationException();
jaroslav@597
   954
        }
jaroslav@597
   955
    }
jaroslav@597
   956
jaroslav@597
   957
    private static class Node<E> {
jaroslav@597
   958
        E item;
jaroslav@597
   959
        Node<E> next;
jaroslav@597
   960
        Node<E> prev;
jaroslav@597
   961
jaroslav@597
   962
        Node(Node<E> prev, E element, Node<E> next) {
jaroslav@597
   963
            this.item = element;
jaroslav@597
   964
            this.next = next;
jaroslav@597
   965
            this.prev = prev;
jaroslav@597
   966
        }
jaroslav@597
   967
    }
jaroslav@597
   968
jaroslav@597
   969
    /**
jaroslav@597
   970
     * @since 1.6
jaroslav@597
   971
     */
jaroslav@597
   972
    public Iterator<E> descendingIterator() {
jaroslav@597
   973
        return new DescendingIterator();
jaroslav@597
   974
    }
jaroslav@597
   975
jaroslav@597
   976
    /**
jaroslav@597
   977
     * Adapter to provide descending iterators via ListItr.previous
jaroslav@597
   978
     */
jaroslav@597
   979
    private class DescendingIterator implements Iterator<E> {
jaroslav@597
   980
        private final ListItr itr = new ListItr(size());
jaroslav@597
   981
        public boolean hasNext() {
jaroslav@597
   982
            return itr.hasPrevious();
jaroslav@597
   983
        }
jaroslav@597
   984
        public E next() {
jaroslav@597
   985
            return itr.previous();
jaroslav@597
   986
        }
jaroslav@597
   987
        public void remove() {
jaroslav@597
   988
            itr.remove();
jaroslav@597
   989
        }
jaroslav@597
   990
    }
jaroslav@597
   991
jaroslav@597
   992
    @SuppressWarnings("unchecked")
jaroslav@597
   993
    private LinkedList<E> superClone() {
jaroslav@597
   994
        try {
jaroslav@597
   995
            return (LinkedList<E>) super.clone();
jaroslav@597
   996
        } catch (CloneNotSupportedException e) {
jaroslav@597
   997
            throw new InternalError();
jaroslav@597
   998
        }
jaroslav@597
   999
    }
jaroslav@597
  1000
jaroslav@597
  1001
    /**
jaroslav@597
  1002
     * Returns a shallow copy of this {@code LinkedList}. (The elements
jaroslav@597
  1003
     * themselves are not cloned.)
jaroslav@597
  1004
     *
jaroslav@597
  1005
     * @return a shallow copy of this {@code LinkedList} instance
jaroslav@597
  1006
     */
jaroslav@597
  1007
    public Object clone() {
jaroslav@597
  1008
        LinkedList<E> clone = superClone();
jaroslav@597
  1009
jaroslav@597
  1010
        // Put clone into "virgin" state
jaroslav@597
  1011
        clone.first = clone.last = null;
jaroslav@597
  1012
        clone.size = 0;
jaroslav@597
  1013
        clone.modCount = 0;
jaroslav@597
  1014
jaroslav@597
  1015
        // Initialize clone with our elements
jaroslav@597
  1016
        for (Node<E> x = first; x != null; x = x.next)
jaroslav@597
  1017
            clone.add(x.item);
jaroslav@597
  1018
jaroslav@597
  1019
        return clone;
jaroslav@597
  1020
    }
jaroslav@597
  1021
jaroslav@597
  1022
    /**
jaroslav@597
  1023
     * Returns an array containing all of the elements in this list
jaroslav@597
  1024
     * in proper sequence (from first to last element).
jaroslav@597
  1025
     *
jaroslav@597
  1026
     * <p>The returned array will be "safe" in that no references to it are
jaroslav@597
  1027
     * maintained by this list.  (In other words, this method must allocate
jaroslav@597
  1028
     * a new array).  The caller is thus free to modify the returned array.
jaroslav@597
  1029
     *
jaroslav@597
  1030
     * <p>This method acts as bridge between array-based and collection-based
jaroslav@597
  1031
     * APIs.
jaroslav@597
  1032
     *
jaroslav@597
  1033
     * @return an array containing all of the elements in this list
jaroslav@597
  1034
     *         in proper sequence
jaroslav@597
  1035
     */
jaroslav@597
  1036
    public Object[] toArray() {
jaroslav@597
  1037
        Object[] result = new Object[size];
jaroslav@597
  1038
        int i = 0;
jaroslav@597
  1039
        for (Node<E> x = first; x != null; x = x.next)
jaroslav@597
  1040
            result[i++] = x.item;
jaroslav@597
  1041
        return result;
jaroslav@597
  1042
    }
jaroslav@597
  1043
jaroslav@597
  1044
    /**
jaroslav@597
  1045
     * Returns an array containing all of the elements in this list in
jaroslav@597
  1046
     * proper sequence (from first to last element); the runtime type of
jaroslav@597
  1047
     * the returned array is that of the specified array.  If the list fits
jaroslav@597
  1048
     * in the specified array, it is returned therein.  Otherwise, a new
jaroslav@597
  1049
     * array is allocated with the runtime type of the specified array and
jaroslav@597
  1050
     * the size of this list.
jaroslav@597
  1051
     *
jaroslav@597
  1052
     * <p>If the list fits in the specified array with room to spare (i.e.,
jaroslav@597
  1053
     * the array has more elements than the list), the element in the array
jaroslav@597
  1054
     * immediately following the end of the list is set to {@code null}.
jaroslav@597
  1055
     * (This is useful in determining the length of the list <i>only</i> if
jaroslav@597
  1056
     * the caller knows that the list does not contain any null elements.)
jaroslav@597
  1057
     *
jaroslav@597
  1058
     * <p>Like the {@link #toArray()} method, this method acts as bridge between
jaroslav@597
  1059
     * array-based and collection-based APIs.  Further, this method allows
jaroslav@597
  1060
     * precise control over the runtime type of the output array, and may,
jaroslav@597
  1061
     * under certain circumstances, be used to save allocation costs.
jaroslav@597
  1062
     *
jaroslav@597
  1063
     * <p>Suppose {@code x} is a list known to contain only strings.
jaroslav@597
  1064
     * The following code can be used to dump the list into a newly
jaroslav@597
  1065
     * allocated array of {@code String}:
jaroslav@597
  1066
     *
jaroslav@597
  1067
     * <pre>
jaroslav@597
  1068
     *     String[] y = x.toArray(new String[0]);</pre>
jaroslav@597
  1069
     *
jaroslav@597
  1070
     * Note that {@code toArray(new Object[0])} is identical in function to
jaroslav@597
  1071
     * {@code toArray()}.
jaroslav@597
  1072
     *
jaroslav@597
  1073
     * @param a the array into which the elements of the list are to
jaroslav@597
  1074
     *          be stored, if it is big enough; otherwise, a new array of the
jaroslav@597
  1075
     *          same runtime type is allocated for this purpose.
jaroslav@597
  1076
     * @return an array containing the elements of the list
jaroslav@597
  1077
     * @throws ArrayStoreException if the runtime type of the specified array
jaroslav@597
  1078
     *         is not a supertype of the runtime type of every element in
jaroslav@597
  1079
     *         this list
jaroslav@597
  1080
     * @throws NullPointerException if the specified array is null
jaroslav@597
  1081
     */
jaroslav@597
  1082
    @SuppressWarnings("unchecked")
jaroslav@597
  1083
    public <T> T[] toArray(T[] a) {
jaroslav@597
  1084
        if (a.length < size)
jaroslav@597
  1085
            a = (T[])java.lang.reflect.Array.newInstance(
jaroslav@597
  1086
                                a.getClass().getComponentType(), size);
jaroslav@597
  1087
        int i = 0;
jaroslav@597
  1088
        Object[] result = a;
jaroslav@597
  1089
        for (Node<E> x = first; x != null; x = x.next)
jaroslav@597
  1090
            result[i++] = x.item;
jaroslav@597
  1091
jaroslav@597
  1092
        if (a.length > size)
jaroslav@597
  1093
            a[size] = null;
jaroslav@597
  1094
jaroslav@597
  1095
        return a;
jaroslav@597
  1096
    }
jaroslav@597
  1097
jaroslav@597
  1098
    private static final long serialVersionUID = 876323262645176354L;
jaroslav@597
  1099
jaroslav@597
  1100
}