ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/LinkedList.java
Revision: 1.27
Committed: Sat May 14 02:19:00 2005 UTC (19 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.26: +77 -79 lines
Log Message:
doc fixes

File Contents

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