ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/LinkedList.java
Revision: 1.42
Committed: Mon Dec 5 02:56:59 2005 UTC (18 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.41: +1 -1 lines
Log Message:
copyright update for 2006

File Contents

# User Rev Content
1 tim 1.1 /*
2 dl 1.6 * %W% %E%
3 tim 1.1 *
4 jsr166 1.42 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
5 tim 1.1 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6     */
7    
8 jsr166 1.24 package java.util;
9 jsr166 1.37 import java.util.*; // for javadoc (till 6280605 is fixed)
10 tim 1.1
11     /**
12     * Linked list implementation of the <tt>List</tt> interface. Implements all
13     * optional list operations, and permits all elements (including
14     * <tt>null</tt>). In addition to implementing the <tt>List</tt> interface,
15     * the <tt>LinkedList</tt> class provides uniformly named methods to
16     * <tt>get</tt>, <tt>remove</tt> and <tt>insert</tt> an element at the
17     * beginning and end of the list. These operations allow linked lists to be
18 dl 1.19 * used as a stack, {@linkplain Queue queue}, or {@linkplain Deque
19     * double-ended queue}. <p>
20 tim 1.1 *
21 dl 1.17 * The class implements the <tt>Deque</tt> interface, providing
22 dl 1.3 * first-in-first-out queue operations for <tt>add</tt>,
23 dl 1.21 * <tt>poll</tt>, along with other stack and deque operations.<p>
24 tim 1.1 *
25     * All of the operations perform as could be expected for a doubly-linked
26     * list. Operations that index into the list will traverse the list from
27 dl 1.8 * the beginning or the end, whichever is closer to the specified index.<p>
28 tim 1.1 *
29 jsr166 1.37 * <p><strong>Note that this implementation is not synchronized.</strong>
30     * If multiple threads access a linked list concurrently, and at least
31     * one of the threads modifies the list structurally, it <i>must</i> be
32     * synchronized externally. (A structural modification is any operation
33     * that adds or deletes one or more elements; merely setting the value of
34     * an element is not a structural modification.) This is typically
35     * accomplished by synchronizing on some object that naturally
36     * encapsulates the list.
37     *
38     * If no such object exists, the list should be "wrapped" using the
39     * {@link Collections#synchronizedList Collections.synchronizedList}
40     * method. This is best done at creation time, to prevent accidental
41     * unsynchronized access to the list:<pre>
42     * List list = Collections.synchronizedList(new LinkedList(...));</pre>
43 tim 1.1 *
44 jsr166 1.24 * <p>The iterators returned by this class's <tt>iterator</tt> and
45 tim 1.1 * <tt>listIterator</tt> methods are <i>fail-fast</i>: if the list is
46 jsr166 1.24 * structurally modified at any time after the iterator is created, in
47     * any way except through the Iterator's own <tt>remove</tt> or
48     * <tt>add</tt> methods, the iterator will throw a {@link
49     * ConcurrentModificationException}. Thus, in the face of concurrent
50     * modification, the iterator fails quickly and cleanly, rather than
51     * risking arbitrary, non-deterministic behavior at an undetermined
52     * time in the future.
53 tim 1.1 *
54     * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
55     * as it is, generally speaking, impossible to make any hard guarantees in the
56     * presence of unsynchronized concurrent modification. Fail-fast iterators
57 dl 1.3 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
58 tim 1.1 * Therefore, it would be wrong to write a program that depended on this
59     * exception for its correctness: <i>the fail-fast behavior of iterators
60 jsr166 1.24 * should be used only to detect bugs.</i>
61 dl 1.3 *
62 jsr166 1.24 * <p>This class is a member of the
63 dl 1.3 * <a href="{@docRoot}/../guide/collections/index.html">
64     * Java Collections Framework</a>.
65 tim 1.1 *
66     * @author Josh Bloch
67 dl 1.6 * @version %I%, %G%
68 jsr166 1.14 * @see List
69     * @see ArrayList
70     * @see Vector
71 tim 1.1 * @since 1.2
72 dl 1.10 * @param <E> the type of elements held in this collection
73 tim 1.1 */
74    
75 dl 1.3 public class LinkedList<E>
76     extends AbstractSequentialList<E>
77 dl 1.17 implements List<E>, Deque<E>, Cloneable, java.io.Serializable
78 tim 1.1 {
79 dl 1.3 private transient Entry<E> header = new Entry<E>(null, null, null);
80 tim 1.1 private transient int size = 0;
81    
82     /**
83     * Constructs an empty list.
84     */
85     public LinkedList() {
86     header.next = header.previous = header;
87     }
88    
89     /**
90     * Constructs a list containing the elements of the specified
91     * collection, in the order they are returned by the collection's
92     * iterator.
93     *
94 jsr166 1.27 * @param c the collection whose elements are to be placed into this list
95     * @throws NullPointerException if the specified collection is null
96 tim 1.1 */
97 jsr166 1.35 public LinkedList(Collection<? extends E> c) {
98     this();
99     addAll(c);
100     }
101 tim 1.1
102     /**
103     * Returns the first element in this list.
104     *
105 jsr166 1.27 * @return the first element in this list
106     * @throws NoSuchElementException if this list is empty
107 tim 1.1 */
108 dl 1.3 public E getFirst() {
109 jsr166 1.14 if (size==0)
110     throw new NoSuchElementException();
111 tim 1.1
112 jsr166 1.14 return header.next.element;
113 tim 1.1 }
114    
115     /**
116     * Returns the last element in this list.
117     *
118 jsr166 1.27 * @return the last element in this list
119     * @throws NoSuchElementException if this list is empty
120 tim 1.1 */
121 dl 1.3 public E getLast() {
122 jsr166 1.14 if (size==0)
123     throw new NoSuchElementException();
124 tim 1.1
125 jsr166 1.14 return header.previous.element;
126 tim 1.1 }
127    
128     /**
129     * Removes and returns the first element from this list.
130     *
131 jsr166 1.27 * @return the first element from this list
132     * @throws NoSuchElementException if this list is empty
133 tim 1.1 */
134 dl 1.3 public E removeFirst() {
135 jsr166 1.14 return remove(header.next);
136 tim 1.1 }
137    
138     /**
139     * Removes and returns the last element from this list.
140     *
141 jsr166 1.27 * @return the last element from this list
142     * @throws NoSuchElementException if this list is empty
143 tim 1.1 */
144 dl 1.3 public E removeLast() {
145 jsr166 1.14 return remove(header.previous);
146 tim 1.1 }
147    
148     /**
149 jsr166 1.36 * Inserts the specified element at the beginning of this list.
150 dl 1.3 *
151 jsr166 1.36 * @param e the element to add
152 tim 1.1 */
153 jsr166 1.25 public void addFirst(E e) {
154     addBefore(e, header.next);
155 tim 1.1 }
156    
157     /**
158 jsr166 1.36 * Appends the specified element to the end of this list.
159     *
160     * <p>This method is equivalent to {@link #add}.
161 dl 1.3 *
162 jsr166 1.36 * @param e the element to add
163 tim 1.1 */
164 jsr166 1.25 public void addLast(E e) {
165     addBefore(e, header);
166 tim 1.1 }
167    
168     /**
169     * Returns <tt>true</tt> if this list contains the specified element.
170     * More formally, returns <tt>true</tt> if and only if this list contains
171 jsr166 1.28 * at least one element <tt>e</tt> such that
172     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
173 tim 1.1 *
174 jsr166 1.27 * @param o element whose presence in this list is to be tested
175     * @return <tt>true</tt> if this list contains the specified element
176 tim 1.1 */
177     public boolean contains(Object o) {
178     return indexOf(o) != -1;
179     }
180    
181     /**
182     * Returns the number of elements in this list.
183     *
184 jsr166 1.27 * @return the number of elements in this list
185 tim 1.1 */
186     public int size() {
187 jsr166 1.14 return size;
188 tim 1.1 }
189    
190     /**
191 jsr166 1.24 * Appends the specified element to the end of this list.
192 tim 1.1 *
193 jsr166 1.36 * <p>This method is equivalent to {@link #addLast}.
194     *
195 jsr166 1.27 * @param e element to be appended to this list
196 jsr166 1.38 * @return <tt>true</tt> (as specified by {@link Collection#add})
197 tim 1.1 */
198 jsr166 1.26 public boolean add(E e) {
199     addBefore(e, header);
200 tim 1.1 return true;
201     }
202    
203     /**
204 jsr166 1.28 * Removes the first occurrence of the specified element from this list,
205     * if it is present. If this list does not contain the element, it is
206     * unchanged. More formally, removes the element with the lowest index
207     * <tt>i</tt> such that
208     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
209     * (if such an element exists). Returns <tt>true</tt> if this list
210     * contained the specified element (or equivalently, if this list
211     * changed as a result of the call).
212 tim 1.1 *
213 jsr166 1.27 * @param o element to be removed from this list, if present
214 jsr166 1.28 * @return <tt>true</tt> if this list contained the specified element
215 tim 1.1 */
216     public boolean remove(Object o) {
217     if (o==null) {
218 dl 1.3 for (Entry<E> e = header.next; e != header; e = e.next) {
219 tim 1.1 if (e.element==null) {
220     remove(e);
221     return true;
222     }
223     }
224     } else {
225 dl 1.3 for (Entry<E> e = header.next; e != header; e = e.next) {
226 tim 1.1 if (o.equals(e.element)) {
227     remove(e);
228     return true;
229     }
230     }
231     }
232     return false;
233     }
234    
235     /**
236 jsr166 1.24 * Appends all of the elements in the specified collection to the end of
237 tim 1.1 * this list, in the order that they are returned by the specified
238     * collection's iterator. The behavior of this operation is undefined if
239     * the specified collection is modified while the operation is in
240 jsr166 1.33 * progress. (Note that this will occur if the specified collection is
241     * this list, and it's nonempty.)
242 tim 1.1 *
243 jsr166 1.31 * @param c collection containing elements to be added to this list
244 jsr166 1.27 * @return <tt>true</tt> if this list changed as a result of the call
245     * @throws NullPointerException if the specified collection is null
246 tim 1.1 */
247 dl 1.3 public boolean addAll(Collection<? extends E> c) {
248 tim 1.1 return addAll(size, c);
249     }
250    
251     /**
252     * Inserts all of the elements in the specified collection into this
253     * list, starting at the specified position. Shifts the element
254     * currently at that position (if any) and any subsequent elements to
255     * the right (increases their indices). The new elements will appear
256     * in the list in the order that they are returned by the
257     * specified collection's iterator.
258     *
259 jsr166 1.27 * @param index index at which to insert the first element
260     * from the specified collection
261 jsr166 1.31 * @param c collection containing elements to be added to this list
262 jsr166 1.27 * @return <tt>true</tt> if this list changed as a result of the call
263 jsr166 1.28 * @throws IndexOutOfBoundsException {@inheritDoc}
264 jsr166 1.27 * @throws NullPointerException if the specified collection is null
265 tim 1.1 */
266 dl 1.3 public boolean addAll(int index, Collection<? extends E> c) {
267 dl 1.4 if (index < 0 || index > size)
268 dl 1.3 throw new IndexOutOfBoundsException("Index: "+index+
269     ", Size: "+size);
270     Object[] a = c.toArray();
271     int numNew = a.length;
272     if (numNew==0)
273     return false;
274 jsr166 1.14 modCount++;
275 dl 1.3
276     Entry<E> successor = (index==size ? header : entry(index));
277     Entry<E> predecessor = successor.previous;
278 jsr166 1.14 for (int i=0; i<numNew; i++) {
279 dl 1.3 Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);
280 tim 1.1 predecessor.next = e;
281     predecessor = e;
282     }
283     successor.previous = predecessor;
284    
285     size += numNew;
286     return true;
287     }
288    
289     /**
290     * Removes all of the elements from this list.
291     */
292     public void clear() {
293 jsr166 1.14 Entry<E> e = header.next;
294     while (e != header) {
295     Entry<E> next = e.next;
296     e.next = e.previous = null;
297     e.element = null;
298     e = next;
299     }
300 tim 1.1 header.next = header.previous = header;
301 jozart 1.12 size = 0;
302 jsr166 1.14 modCount++;
303 tim 1.1 }
304    
305    
306     // Positional Access Operations
307    
308     /**
309     * Returns the element at the specified position in this list.
310     *
311 jsr166 1.28 * @param index index of the element to return
312 jsr166 1.27 * @return the element at the specified position in this list
313 jsr166 1.28 * @throws IndexOutOfBoundsException {@inheritDoc}
314 tim 1.1 */
315 dl 1.3 public E get(int index) {
316 tim 1.1 return entry(index).element;
317     }
318    
319     /**
320     * Replaces the element at the specified position in this list with the
321     * specified element.
322     *
323 jsr166 1.28 * @param index index of the element to replace
324 jsr166 1.27 * @param element element to be stored at the specified position
325     * @return the element previously at the specified position
326 jsr166 1.28 * @throws IndexOutOfBoundsException {@inheritDoc}
327 tim 1.1 */
328 dl 1.3 public E set(int index, E element) {
329     Entry<E> e = entry(index);
330     E oldVal = e.element;
331 tim 1.1 e.element = element;
332     return oldVal;
333     }
334    
335     /**
336     * Inserts the specified element at the specified position in this list.
337     * Shifts the element currently at that position (if any) and any
338     * subsequent elements to the right (adds one to their indices).
339     *
340 jsr166 1.27 * @param index index at which the specified element is to be inserted
341     * @param element element to be inserted
342 jsr166 1.28 * @throws IndexOutOfBoundsException {@inheritDoc}
343 tim 1.1 */
344 dl 1.3 public void add(int index, E element) {
345 tim 1.1 addBefore(element, (index==size ? header : entry(index)));
346     }
347    
348     /**
349     * Removes the element at the specified position in this list. Shifts any
350     * subsequent elements to the left (subtracts one from their indices).
351     * Returns the element that was removed from the list.
352     *
353 jsr166 1.27 * @param index the index of the element to be removed
354     * @return the element previously at the specified position
355 jsr166 1.28 * @throws IndexOutOfBoundsException {@inheritDoc}
356 tim 1.1 */
357 dl 1.3 public E remove(int index) {
358 jsr166 1.14 return remove(entry(index));
359 tim 1.1 }
360    
361     /**
362 jsr166 1.24 * Returns the indexed entry.
363 tim 1.1 */
364 dl 1.3 private Entry<E> entry(int index) {
365 tim 1.1 if (index < 0 || index >= size)
366     throw new IndexOutOfBoundsException("Index: "+index+
367     ", Size: "+size);
368 dl 1.3 Entry<E> e = header;
369 tim 1.1 if (index < (size >> 1)) {
370     for (int i = 0; i <= index; i++)
371     e = e.next;
372     } else {
373     for (int i = size; i > index; i--)
374     e = e.previous;
375     }
376     return e;
377     }
378    
379    
380     // Search Operations
381    
382     /**
383 jsr166 1.29 * Returns the index of the first occurrence of the specified element
384     * in this list, or -1 if this list does not contain the element.
385     * More formally, returns the lowest index <tt>i</tt> such that
386     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
387     * or -1 if there is no such index.
388 tim 1.1 *
389 jsr166 1.27 * @param o element to search for
390 jsr166 1.29 * @return the index of the first occurrence of the specified element in
391     * this list, or -1 if this list does not contain the element
392 tim 1.1 */
393     public int indexOf(Object o) {
394     int index = 0;
395     if (o==null) {
396     for (Entry e = header.next; e != header; e = e.next) {
397     if (e.element==null)
398     return index;
399     index++;
400     }
401     } else {
402     for (Entry e = header.next; e != header; e = e.next) {
403     if (o.equals(e.element))
404     return index;
405     index++;
406     }
407     }
408     return -1;
409     }
410    
411     /**
412 jsr166 1.29 * Returns the index of the last occurrence of the specified element
413     * in this list, or -1 if this list does not contain the element.
414     * More formally, returns the highest index <tt>i</tt> such that
415     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
416     * or -1 if there is no such index.
417 tim 1.1 *
418 jsr166 1.27 * @param o element to search for
419 jsr166 1.29 * @return the index of the last occurrence of the specified element in
420     * this list, or -1 if this list does not contain the element
421 tim 1.1 */
422     public int lastIndexOf(Object o) {
423     int index = size;
424     if (o==null) {
425     for (Entry e = header.previous; e != header; e = e.previous) {
426     index--;
427     if (e.element==null)
428     return index;
429     }
430     } else {
431     for (Entry e = header.previous; e != header; e = e.previous) {
432     index--;
433     if (o.equals(e.element))
434     return index;
435     }
436     }
437     return -1;
438     }
439    
440 dl 1.3 // Queue operations.
441    
442     /**
443 dl 1.7 * Retrieves, but does not remove, the head (first element) of this list.
444 jsr166 1.27 * @return the head of this list, or <tt>null</tt> if this list is empty
445 dl 1.7 * @since 1.5
446 dl 1.3 */
447     public E peek() {
448     if (size==0)
449     return null;
450     return getFirst();
451     }
452    
453     /**
454 dl 1.7 * Retrieves, but does not remove, the head (first element) of this list.
455 jsr166 1.27 * @return the head of this list
456     * @throws NoSuchElementException if this list is empty
457 dl 1.7 * @since 1.5
458 dl 1.3 */
459     public E element() {
460     return getFirst();
461     }
462    
463     /**
464 jsr166 1.27 * Retrieves and removes the head (first element) of this list
465     * @return the head of this list, or <tt>null</tt> if this list is empty
466 dl 1.7 * @since 1.5
467 dl 1.3 */
468     public E poll() {
469     if (size==0)
470     return null;
471     return removeFirst();
472     }
473    
474     /**
475 dl 1.7 * Retrieves and removes the head (first element) of this list.
476 jsr166 1.27 *
477     * @return the head of this list
478     * @throws NoSuchElementException if this list is empty
479 dl 1.7 * @since 1.5
480 dl 1.3 */
481     public E remove() {
482     return removeFirst();
483     }
484    
485     /**
486     * Adds the specified element as the tail (last element) of this list.
487     *
488 jsr166 1.27 * @param e the element to add
489 jsr166 1.38 * @return <tt>true</tt> (as specified by {@link Queue#offer})
490 dl 1.7 * @since 1.5
491 dl 1.3 */
492 jsr166 1.26 public boolean offer(E e) {
493     return add(e);
494 dl 1.3 }
495    
496 dl 1.17 // Deque operations
497     /**
498 dl 1.22 * Inserts the specified element at the front of this list.
499 dl 1.17 *
500 dl 1.22 * @param e the element to insert
501 jsr166 1.38 * @return <tt>true</tt> (as specified by {@link Deque#offerFirst})
502 dl 1.17 * @since 1.6
503     */
504 dl 1.22 public boolean offerFirst(E e) {
505     addFirst(e);
506 dl 1.17 return true;
507     }
508    
509     /**
510 dl 1.22 * Inserts the specified element at the end of this list.
511 dl 1.17 *
512 dl 1.22 * @param e the element to insert
513 jsr166 1.39 * @return <tt>true</tt> (as specified by {@link Deque#offerLast})
514 dl 1.17 * @since 1.6
515     */
516 dl 1.22 public boolean offerLast(E e) {
517     addLast(e);
518 dl 1.17 return true;
519     }
520    
521     /**
522 dl 1.19 * Retrieves, but does not remove, the first element of this list,
523 jsr166 1.27 * or returns <tt>null</tt> if this list is empty.
524 dl 1.17 *
525 jsr166 1.27 * @return the first element of this list, or <tt>null</tt>
526 jsr166 1.28 * if this list is empty
527 dl 1.17 * @since 1.6
528     */
529     public E peekFirst() {
530     if (size==0)
531     return null;
532 dl 1.18 return getFirst();
533 dl 1.17 }
534    
535     /**
536 dl 1.19 * Retrieves, but does not remove, the last element of this list,
537 jsr166 1.27 * or returns <tt>null</tt> if this list is empty.
538 dl 1.17 *
539 jsr166 1.27 * @return the last element of this list, or <tt>null</tt>
540 jsr166 1.28 * if this list is empty
541 dl 1.17 * @since 1.6
542     */
543     public E peekLast() {
544     if (size==0)
545     return null;
546 dl 1.18 return getLast();
547 dl 1.17 }
548    
549     /**
550 jsr166 1.39 * Retrieves and removes the first element of this list,
551     * or returns <tt>null</tt> if this list is empty.
552 dl 1.17 *
553 dl 1.19 * @return the first element of this list, or <tt>null</tt> if
554     * this list is empty
555 dl 1.17 * @since 1.6
556     */
557     public E pollFirst() {
558     if (size==0)
559     return null;
560     return removeFirst();
561     }
562    
563     /**
564 jsr166 1.39 * Retrieves and removes the last element of this list,
565     * or returns <tt>null</tt> if this list is empty.
566 dl 1.17 *
567 dl 1.19 * @return the last element of this list, or <tt>null</tt> if
568     * this list is empty
569 dl 1.17 * @since 1.6
570     */
571     public E pollLast() {
572     if (size==0)
573     return null;
574     return removeLast();
575     }
576    
577     /**
578 dl 1.19 * Pushes an element onto the stack represented by this list. In other
579 dl 1.22 * words, inserts the element at the front of this list.
580 dl 1.17 *
581     * <p>This method is equivalent to {@link #addFirst}.
582     *
583 dl 1.22 * @param e the element to push
584 dl 1.17 * @since 1.6
585     */
586 dl 1.22 public void push(E e) {
587     addFirst(e);
588 dl 1.17 }
589    
590     /**
591 dl 1.19 * Pops an element from the stack represented by this list. In other
592 dl 1.20 * words, removes and returns the first element of this list.
593 dl 1.17 *
594     * <p>This method is equivalent to {@link #removeFirst()}.
595     *
596 dl 1.19 * @return the element at the front of this list (which is the top
597 jsr166 1.27 * of the stack represented by this list)
598     * @throws NoSuchElementException if this list is empty
599 dl 1.17 * @since 1.6
600     */
601     public E pop() {
602     return removeFirst();
603     }
604    
605     /**
606     * Removes the first occurrence of the specified element in this
607 dl 1.19 * list (when traversing the list from head to tail). If the list
608 dl 1.17 * does not contain the element, it is unchanged.
609     *
610 dl 1.21 * @param o element to be removed from this list, if present
611 dl 1.19 * @return <tt>true</tt> if the list contained the specified element
612 dl 1.17 * @since 1.6
613     */
614 dl 1.21 public boolean removeFirstOccurrence(Object o) {
615     return remove(o);
616 dl 1.17 }
617    
618     /**
619     * Removes the last occurrence of the specified element in this
620 dl 1.19 * list (when traversing the list from head to tail). If the list
621 dl 1.17 * does not contain the element, it is unchanged.
622     *
623 dl 1.19 * @param o element to be removed from this list, if present
624     * @return <tt>true</tt> if the list contained the specified element
625 dl 1.17 * @since 1.6
626     */
627     public boolean removeLastOccurrence(Object o) {
628     if (o==null) {
629 dl 1.34 for (Entry<E> e = header.previous; e != header; e = e.previous) {
630 dl 1.17 if (e.element==null) {
631     remove(e);
632     return true;
633     }
634     }
635     } else {
636 dl 1.34 for (Entry<E> e = header.previous; e != header; e = e.previous) {
637 dl 1.17 if (o.equals(e.element)) {
638     remove(e);
639     return true;
640     }
641     }
642     }
643     return false;
644     }
645    
646 tim 1.1 /**
647     * Returns a list-iterator of the elements in this list (in proper
648     * sequence), starting at the specified position in the list.
649     * Obeys the general contract of <tt>List.listIterator(int)</tt>.<p>
650     *
651     * The list-iterator is <i>fail-fast</i>: if the list is structurally
652     * modified at any time after the Iterator is created, in any way except
653     * through the list-iterator's own <tt>remove</tt> or <tt>add</tt>
654     * methods, the list-iterator will throw a
655     * <tt>ConcurrentModificationException</tt>. Thus, in the face of
656     * concurrent modification, the iterator fails quickly and cleanly, rather
657     * than risking arbitrary, non-deterministic behavior at an undetermined
658     * time in the future.
659     *
660 jsr166 1.27 * @param index index of the first element to be returned from the
661 jsr166 1.28 * list-iterator (by a call to <tt>next</tt>)
662 tim 1.1 * @return a ListIterator of the elements in this list (in proper
663 jsr166 1.28 * sequence), starting at the specified position in the list
664     * @throws IndexOutOfBoundsException {@inheritDoc}
665 dl 1.3 * @see List#listIterator(int)
666 tim 1.1 */
667 dl 1.3 public ListIterator<E> listIterator(int index) {
668 jsr166 1.14 return new ListItr(index);
669 tim 1.1 }
670    
671 dl 1.3 private class ListItr implements ListIterator<E> {
672 jsr166 1.14 private Entry<E> lastReturned = header;
673     private Entry<E> next;
674     private int nextIndex;
675     private int expectedModCount = modCount;
676    
677     ListItr(int index) {
678     if (index < 0 || index > size)
679     throw new IndexOutOfBoundsException("Index: "+index+
680     ", Size: "+size);
681     if (index < (size >> 1)) {
682     next = header.next;
683     for (nextIndex=0; nextIndex<index; nextIndex++)
684     next = next.next;
685     } else {
686     next = header;
687     for (nextIndex=size; nextIndex>index; nextIndex--)
688     next = next.previous;
689     }
690     }
691    
692     public boolean hasNext() {
693     return nextIndex != size;
694     }
695    
696     public E next() {
697     checkForComodification();
698     if (nextIndex == size)
699     throw new NoSuchElementException();
700    
701     lastReturned = next;
702     next = next.next;
703     nextIndex++;
704     return lastReturned.element;
705     }
706    
707     public boolean hasPrevious() {
708     return nextIndex != 0;
709     }
710    
711     public E previous() {
712     if (nextIndex == 0)
713     throw new NoSuchElementException();
714    
715     lastReturned = next = next.previous;
716     nextIndex--;
717     checkForComodification();
718     return lastReturned.element;
719     }
720    
721     public int nextIndex() {
722     return nextIndex;
723     }
724    
725     public int previousIndex() {
726     return nextIndex-1;
727     }
728 jozart 1.12
729 jsr166 1.14 public void remove() {
730 tim 1.1 checkForComodification();
731 jsr166 1.14 Entry<E> lastNext = lastReturned.next;
732 tim 1.1 try {
733     LinkedList.this.remove(lastReturned);
734     } catch (NoSuchElementException e) {
735     throw new IllegalStateException();
736     }
737 jsr166 1.14 if (next==lastReturned)
738     next = lastNext;
739 tim 1.1 else
740 jsr166 1.14 nextIndex--;
741     lastReturned = header;
742     expectedModCount++;
743     }
744    
745 jsr166 1.26 public void set(E e) {
746 jsr166 1.14 if (lastReturned == header)
747     throw new IllegalStateException();
748     checkForComodification();
749 jsr166 1.26 lastReturned.element = e;
750 jsr166 1.14 }
751    
752 jsr166 1.26 public void add(E e) {
753 jsr166 1.14 checkForComodification();
754     lastReturned = header;
755 jsr166 1.26 addBefore(e, next);
756 jsr166 1.14 nextIndex++;
757     expectedModCount++;
758     }
759    
760     final void checkForComodification() {
761     if (modCount != expectedModCount)
762     throw new ConcurrentModificationException();
763     }
764 dl 1.3 }
765    
766     private static class Entry<E> {
767 jsr166 1.14 E element;
768     Entry<E> next;
769     Entry<E> previous;
770    
771     Entry(E element, Entry<E> next, Entry<E> previous) {
772     this.element = element;
773     this.next = next;
774     this.previous = previous;
775     }
776 dl 1.3 }
777    
778 jsr166 1.26 private Entry<E> addBefore(E e, Entry<E> entry) {
779     Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
780 jsr166 1.14 newEntry.previous.next = newEntry;
781     newEntry.next.previous = newEntry;
782     size++;
783     modCount++;
784     return newEntry;
785     }
786    
787     private E remove(Entry<E> e) {
788     if (e == header)
789     throw new NoSuchElementException();
790    
791     E result = e.element;
792     e.previous.next = e.next;
793     e.next.previous = e.previous;
794     e.next = e.previous = null;
795     e.element = null;
796     size--;
797     modCount++;
798     return result;
799 tim 1.1 }
800    
801 dl 1.40 public Iterator<E> descendingIterator() {
802     return new DescendingIterator();
803     }
804    
805     /** Adapter to provide descending iterators via ListItr.previous */
806     private class DescendingIterator implements Iterator {
807     final ListItr itr = new ListItr(size());
808     public boolean hasNext() {
809     return itr.hasPrevious();
810     }
811     public E next() {
812     return itr.previous();
813     }
814     public void remove() {
815     itr.remove();
816     }
817     }
818    
819     /**
820 tim 1.1 * Returns a shallow copy of this <tt>LinkedList</tt>. (The elements
821     * themselves are not cloned.)
822     *
823 jsr166 1.27 * @return a shallow copy of this <tt>LinkedList</tt> instance
824 tim 1.1 */
825     public Object clone() {
826 dl 1.3 LinkedList<E> clone = null;
827 jsr166 1.14 try {
828     clone = (LinkedList<E>) super.clone();
829     } catch (CloneNotSupportedException e) {
830     throw new InternalError();
831     }
832 tim 1.1
833     // Put clone into "virgin" state
834 dl 1.3 clone.header = new Entry<E>(null, null, null);
835 tim 1.1 clone.header.next = clone.header.previous = clone.header;
836     clone.size = 0;
837     clone.modCount = 0;
838    
839     // Initialize clone with our elements
840 dl 1.3 for (Entry<E> e = header.next; e != header; e = e.next)
841 tim 1.1 clone.add(e.element);
842    
843     return clone;
844     }
845    
846     /**
847     * Returns an array containing all of the elements in this list
848 jsr166 1.29 * in proper sequence (from first to last element).
849 tim 1.1 *
850 jsr166 1.29 * <p>The returned array will be "safe" in that no references to it are
851     * maintained by this list. (In other words, this method must allocate
852     * a new array). The caller is thus free to modify the returned array.
853 jsr166 1.32 *
854 jsr166 1.30 * <p>This method acts as bridge between array-based and collection-based
855     * APIs.
856     *
857 tim 1.1 * @return an array containing all of the elements in this list
858 jsr166 1.29 * in proper sequence
859 tim 1.1 */
860     public Object[] toArray() {
861 jsr166 1.14 Object[] result = new Object[size];
862 tim 1.1 int i = 0;
863 dl 1.3 for (Entry<E> e = header.next; e != header; e = e.next)
864 tim 1.1 result[i++] = e.element;
865 jsr166 1.14 return result;
866 tim 1.1 }
867    
868     /**
869     * Returns an array containing all of the elements in this list in
870 jsr166 1.29 * proper sequence (from first to last element); the runtime type of
871     * the returned array is that of the specified array. If the list fits
872     * in the specified array, it is returned therein. Otherwise, a new
873     * array is allocated with the runtime type of the specified array and
874     * the size of this list.
875     *
876     * <p>If the list fits in the specified array with room to spare (i.e.,
877     * the array has more elements than the list), the element in the array
878     * immediately following the end of the list is set to <tt>null</tt>.
879     * (This is useful in determining the length of the list <i>only</i> if
880     * the caller knows that the list does not contain any null elements.)
881     *
882     * <p>Like the {@link #toArray()} method, this method acts as bridge between
883     * array-based and collection-based APIs. Further, this method allows
884     * precise control over the runtime type of the output array, and may,
885     * under certain circumstances, be used to save allocation costs.
886     *
887     * <p>Suppose <tt>x</tt> is a list known to contain only strings.
888     * The following code can be used to dump the list into a newly
889     * allocated array of <tt>String</tt>:
890     *
891     * <pre>
892     * String[] y = x.toArray(new String[0]);</pre>
893     *
894     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
895     * <tt>toArray()</tt>.
896 tim 1.1 *
897     * @param a the array into which the elements of the list are to
898 jsr166 1.27 * be stored, if it is big enough; otherwise, a new array of the
899     * same runtime type is allocated for this purpose.
900     * @return an array containing the elements of the list
901 jsr166 1.29 * @throws ArrayStoreException if the runtime type of the specified array
902     * is not a supertype of the runtime type of every element in
903     * this list
904 jsr166 1.27 * @throws NullPointerException if the specified array is null
905 tim 1.1 */
906 dl 1.3 public <T> T[] toArray(T[] a) {
907 tim 1.1 if (a.length < size)
908 dl 1.3 a = (T[])java.lang.reflect.Array.newInstance(
909 tim 1.1 a.getClass().getComponentType(), size);
910     int i = 0;
911 jsr166 1.14 Object[] result = a;
912 dl 1.3 for (Entry<E> e = header.next; e != header; e = e.next)
913     result[i++] = e.element;
914 tim 1.1
915     if (a.length > size)
916     a[size] = null;
917    
918     return a;
919     }
920    
921     private static final long serialVersionUID = 876323262645176354L;
922    
923     /**
924     * Save the state of this <tt>LinkedList</tt> instance to a stream (that
925     * is, serialize it).
926     *
927     * @serialData The size of the list (the number of elements it
928 jsr166 1.27 * contains) is emitted (int), followed by all of its
929     * elements (each an Object) in the proper order.
930 tim 1.1 */
931 dl 1.3 private void writeObject(java.io.ObjectOutputStream s)
932 tim 1.1 throws java.io.IOException {
933 jsr166 1.14 // Write out any hidden serialization magic
934     s.defaultWriteObject();
935 tim 1.1
936     // Write out size
937     s.writeInt(size);
938    
939 jsr166 1.14 // Write out all elements in the proper order.
940 tim 1.1 for (Entry e = header.next; e != header; e = e.next)
941     s.writeObject(e.element);
942     }
943    
944     /**
945     * Reconstitute this <tt>LinkedList</tt> instance from a stream (that is
946     * deserialize it).
947     */
948 dl 1.3 private void readObject(java.io.ObjectInputStream s)
949 tim 1.1 throws java.io.IOException, ClassNotFoundException {
950 jsr166 1.14 // Read in any hidden serialization magic
951     s.defaultReadObject();
952 tim 1.1
953     // Read in size
954     int size = s.readInt();
955    
956     // Initialize header
957 dl 1.3 header = new Entry<E>(null, null, null);
958 tim 1.1 header.next = header.previous = header;
959    
960 jsr166 1.14 // Read in all elements in the proper order.
961     for (int i=0; i<size; i++)
962 dl 1.3 addBefore((E)s.readObject(), header);
963 tim 1.1 }
964     }