ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/LinkedList.java
Revision: 1.21
Committed: Tue Mar 8 12:27:06 2005 UTC (19 years, 2 months ago) by dl
Branch: MAIN
Changes since 1.20: +13 -13 lines
Log Message:
Copyedit pass

File Contents

# User Rev Content
1 tim 1.1 /*
2 dl 1.6 * %W% %E%
3 tim 1.1 *
4 jsr166 1.15 * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5 tim 1.1 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6     */
7    
8 dl 1.17 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     * </pre><p>
40     *
41     * The iterators returned by the this class's <tt>iterator</tt> and
42     * <tt>listIterator</tt> methods are <i>fail-fast</i>: if the list is
43     * structurally modified at any time after the iterator is created, in any way
44     * except through the Iterator's own <tt>remove</tt> or <tt>add</tt> methods,
45     * the iterator will throw a <tt>ConcurrentModificationException</tt>. Thus,
46     * in the face of concurrent modification, the iterator fails quickly and
47     * cleanly, rather than risking arbitrary, non-deterministic behavior at an
48     * undetermined time in the future.
49     *
50     * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
51     * as it is, generally speaking, impossible to make any hard guarantees in the
52     * presence of unsynchronized concurrent modification. Fail-fast iterators
53 dl 1.3 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
54 tim 1.1 * Therefore, it would be wrong to write a program that depended on this
55     * exception for its correctness: <i>the fail-fast behavior of iterators
56 dl 1.3 * should be used only to detect bugs.</i><p>
57     *
58     * This class is a member of the
59     * <a href="{@docRoot}/../guide/collections/index.html">
60     * Java Collections Framework</a>.
61 tim 1.1 *
62     * @author Josh Bloch
63 dl 1.6 * @version %I%, %G%
64 jsr166 1.14 * @see List
65     * @see ArrayList
66     * @see Vector
67     * @see Collections#synchronizedList(List)
68 tim 1.1 * @since 1.2
69 dl 1.10 * @param <E> the type of elements held in this collection
70 tim 1.1 */
71    
72 dl 1.3 public class LinkedList<E>
73     extends AbstractSequentialList<E>
74 dl 1.17 implements List<E>, Deque<E>, Cloneable, java.io.Serializable
75 tim 1.1 {
76 dl 1.3 private transient Entry<E> header = new Entry<E>(null, null, null);
77 tim 1.1 private transient int size = 0;
78    
79     /**
80     * Constructs an empty list.
81     */
82     public LinkedList() {
83     header.next = header.previous = header;
84     }
85    
86     /**
87     * Constructs a list containing the elements of the specified
88     * collection, in the order they are returned by the collection's
89     * iterator.
90     *
91     * @param c the collection whose elements are to be placed into this list.
92     * @throws NullPointerException if the specified collection is null.
93     */
94 jsr166 1.14 public LinkedList(Collection<? extends E> c) {
95     this();
96     addAll(c);
97     }
98 tim 1.1
99     /**
100     * Returns the first element in this list.
101     *
102     * @return the first element in this list.
103     * @throws NoSuchElementException if this list is empty.
104     */
105 dl 1.3 public E getFirst() {
106 jsr166 1.14 if (size==0)
107     throw new NoSuchElementException();
108 tim 1.1
109 jsr166 1.14 return header.next.element;
110 tim 1.1 }
111    
112     /**
113     * Returns the last element in this list.
114     *
115     * @return the last element in this list.
116     * @throws NoSuchElementException if this list is empty.
117     */
118 dl 1.3 public E getLast() {
119 jsr166 1.14 if (size==0)
120     throw new NoSuchElementException();
121 tim 1.1
122 jsr166 1.14 return header.previous.element;
123 tim 1.1 }
124    
125     /**
126     * Removes and returns the first element from this list.
127     *
128     * @return the first element from this list.
129     * @throws NoSuchElementException if this list is empty.
130     */
131 dl 1.3 public E removeFirst() {
132 jsr166 1.14 return remove(header.next);
133 tim 1.1 }
134    
135     /**
136     * Removes and returns the last element from this list.
137     *
138     * @return the last element from this list.
139     * @throws NoSuchElementException if this list is empty.
140     */
141 dl 1.3 public E removeLast() {
142 jsr166 1.14 return remove(header.previous);
143 tim 1.1 }
144    
145     /**
146     * Inserts the given element at the beginning of this list.
147 dl 1.3 *
148 tim 1.1 * @param o the element to be inserted at the beginning of this list.
149     */
150 dl 1.3 public void addFirst(E o) {
151 jsr166 1.14 addBefore(o, header.next);
152 tim 1.1 }
153    
154     /**
155     * Appends the given element to the end of this list. (Identical in
156     * function to the <tt>add</tt> method; included only for consistency.)
157 dl 1.3 *
158 tim 1.1 * @param o the element to be inserted at the end of this list.
159     */
160 dl 1.3 public void addLast(E o) {
161 jsr166 1.14 addBefore(o, header);
162 tim 1.1 }
163    
164     /**
165     * Returns <tt>true</tt> if this list contains the specified element.
166     * More formally, returns <tt>true</tt> if and only if this list contains
167     * at least one element <tt>e</tt> such that <tt>(o==null ? e==null
168     * : o.equals(e))</tt>.
169     *
170     * @param o element whose presence in this list is to be tested.
171     * @return <tt>true</tt> if this list contains the specified element.
172     */
173     public boolean contains(Object o) {
174     return indexOf(o) != -1;
175     }
176    
177     /**
178     * Returns the number of elements in this list.
179     *
180     * @return the number of elements in this list.
181     */
182     public int size() {
183 jsr166 1.14 return size;
184 tim 1.1 }
185    
186     /**
187     * Appends the specified element to the end of this list.
188     *
189     * @param o element to be appended to this list.
190     * @return <tt>true</tt> (as per the general contract of
191     * <tt>Collection.add</tt>).
192     */
193 dl 1.3 public boolean add(E o) {
194 jsr166 1.14 addBefore(o, 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     * @param o element to be removed from this list, if present.
206     * @return <tt>true</tt> if the list contained the specified element.
207     */
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     * Appends all of the elements in the specified collection to the end of
229     * 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     * @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     */
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     * @param index index at which to insert first element
252 jsr166 1.14 * from the specified collection.
253 tim 1.1 * @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     * @throws IndexOutOfBoundsException if the specified index is out of
256     * range (<tt>index &lt; 0 || index &gt; size()</tt>).
257     * @throws NullPointerException if the specified collection is null.
258     */
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     * @param index index of element to return.
305     * @return the element at the specified position in this list.
306 dl 1.3 *
307 jsr166 1.15 * @throws IndexOutOfBoundsException if the specified index is out of
308 tim 1.1 * range (<tt>index &lt; 0 || index &gt;= size()</tt>).
309     */
310 dl 1.3 public E get(int index) {
311 tim 1.1 return entry(index).element;
312     }
313    
314     /**
315     * Replaces the element at the specified position in this list with the
316     * specified element.
317     *
318     * @param index index of element to replace.
319     * @param element element to be stored at the specified position.
320     * @return the element previously at the specified position.
321     * @throws IndexOutOfBoundsException if the specified index is out of
322 jsr166 1.14 * range (<tt>index &lt; 0 || index &gt;= size()</tt>).
323 tim 1.1 */
324 dl 1.3 public E set(int index, E element) {
325     Entry<E> e = entry(index);
326     E oldVal = e.element;
327 tim 1.1 e.element = element;
328     return oldVal;
329     }
330    
331     /**
332     * Inserts the specified element at the specified position in this list.
333     * Shifts the element currently at that position (if any) and any
334     * subsequent elements to the right (adds one to their indices).
335     *
336     * @param index index at which the specified element is to be inserted.
337     * @param element element to be inserted.
338 dl 1.3 *
339 tim 1.1 * @throws IndexOutOfBoundsException if the specified index is out of
340 jsr166 1.14 * range (<tt>index &lt; 0 || index &gt; size()</tt>).
341 tim 1.1 */
342 dl 1.3 public void add(int index, E element) {
343 tim 1.1 addBefore(element, (index==size ? header : entry(index)));
344     }
345    
346     /**
347     * Removes the element at the specified position in this list. Shifts any
348     * subsequent elements to the left (subtracts one from their indices).
349     * Returns the element that was removed from the list.
350     *
351     * @param index the index of the element to removed.
352     * @return the element previously at the specified position.
353 dl 1.3 *
354 tim 1.1 * @throws IndexOutOfBoundsException if the specified index is out of
355 jsr166 1.14 * range (<tt>index &lt; 0 || index &gt;= size()</tt>).
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     * Return the indexed entry.
363     */
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     * Returns the index in this list of the first occurrence of the
384     * specified element, or -1 if the List does not contain this
385     * element. More formally, returns the lowest index i such that
386     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, or -1 if
387     * there is no such index.
388     *
389     * @param o element to search for.
390     * @return the index in this list of the first occurrence of the
391 jsr166 1.14 * specified element, or -1 if the list does not contain this
392     * element.
393 tim 1.1 */
394     public int indexOf(Object o) {
395     int index = 0;
396     if (o==null) {
397     for (Entry e = header.next; e != header; e = e.next) {
398     if (e.element==null)
399     return index;
400     index++;
401     }
402     } else {
403     for (Entry e = header.next; e != header; e = e.next) {
404     if (o.equals(e.element))
405     return index;
406     index++;
407     }
408     }
409     return -1;
410     }
411    
412     /**
413     * Returns the index in this list of the last occurrence of the
414     * specified element, or -1 if the list does not contain this
415     * element. More formally, returns the highest index i such that
416     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, or -1 if
417     * there is no such index.
418     *
419     * @param o element to search for.
420     * @return the index in this list of the last occurrence of the
421 jsr166 1.14 * specified element, or -1 if the list does not contain this
422     * element.
423 tim 1.1 */
424     public int lastIndexOf(Object o) {
425     int index = size;
426     if (o==null) {
427     for (Entry e = header.previous; e != header; e = e.previous) {
428     index--;
429     if (e.element==null)
430     return index;
431     }
432     } else {
433     for (Entry e = header.previous; e != header; e = e.previous) {
434     index--;
435     if (o.equals(e.element))
436     return index;
437     }
438     }
439     return -1;
440     }
441    
442 dl 1.3 // Queue operations.
443    
444     /**
445 dl 1.7 * Retrieves, but does not remove, the head (first element) of this list.
446 dl 1.19 * @return the head of this list, or <tt>null</tt> if this list is empty.
447 dl 1.7 * @since 1.5
448 dl 1.3 */
449     public E peek() {
450     if (size==0)
451     return null;
452     return getFirst();
453     }
454    
455     /**
456 dl 1.7 * Retrieves, but does not remove, the head (first element) of this list.
457 dl 1.19 * @return the head of this list.
458     * @throws NoSuchElementException if this list is empty.
459 dl 1.7 * @since 1.5
460 dl 1.3 */
461     public E element() {
462     return getFirst();
463     }
464    
465     /**
466 dl 1.7 * Retrieves and removes the head (first element) of this list.
467 dl 1.19 * @return the head of this list, or <tt>null</tt> if this list is empty.
468 dl 1.7 * @since 1.5
469 dl 1.3 */
470     public E poll() {
471     if (size==0)
472     return null;
473     return removeFirst();
474     }
475    
476     /**
477 dl 1.7 * Retrieves and removes the head (first element) of this list.
478 dl 1.19 * @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.11 * @param o the element to add.
490 dl 1.3 * @return <tt>true</tt> (as per the general contract of
491     * <tt>Queue.offer</tt>)
492 dl 1.7 * @since 1.5
493 dl 1.3 */
494 jsr166 1.11 public boolean offer(E o) {
495     return add(o);
496 dl 1.3 }
497    
498 dl 1.17 // Deque operations
499     /**
500 dl 1.19 * Inserts the specified element to the front of this list.
501 dl 1.17 *
502 dl 1.21 * @param o the element to insert
503 dl 1.17 * @return <tt>true</tt> (as per the spec for {@link Deque#offerFirst})
504     * @since 1.6
505     */
506 dl 1.21 public boolean offerFirst(E o) {
507     addFirst(o);
508 dl 1.17 return true;
509     }
510    
511     /**
512 dl 1.19 * Inserts the specified element to the end of this list.
513 dl 1.17 *
514 dl 1.21 * @param o the element to insert
515 dl 1.17 * @return <tt>true</tt> (as per the spec for {@link Deque#offerLast})
516     * @since 1.6
517     */
518 dl 1.21 public boolean offerLast(E o) {
519     addLast(o);
520 dl 1.17 return true;
521     }
522    
523     /**
524 dl 1.19 * Retrieves, but does not remove, the first element of this list,
525     * returning <tt>null</tt> if this list is empty.
526 dl 1.17 *
527 dl 1.19 * @return the first element of this list, or <tt>null</tt> if
528     * this list is empty
529 dl 1.17 * @since 1.6
530     */
531     public E peekFirst() {
532     if (size==0)
533     return null;
534 dl 1.18 return getFirst();
535 dl 1.17 }
536    
537     /**
538 dl 1.19 * Retrieves, but does not remove, the last element of this list,
539     * returning <tt>null</tt> if this list is empty.
540 dl 1.17 *
541 dl 1.19 * @return the last element of this list, or <tt>null</tt> if this list
542 dl 1.17 * is empty
543     * @since 1.6
544     */
545     public E peekLast() {
546     if (size==0)
547     return null;
548 dl 1.18 return getLast();
549 dl 1.17 }
550    
551     /**
552 dl 1.19 * Retrieves and removes the first element of this list, or
553     * <tt>null</tt> if this list is empty.
554 dl 1.17 *
555 dl 1.19 * @return the first element of this list, or <tt>null</tt> if
556     * this list is empty
557 dl 1.17 * @since 1.6
558     */
559     public E pollFirst() {
560     if (size==0)
561     return null;
562     return removeFirst();
563     }
564    
565     /**
566 dl 1.19 * Retrieves and removes the last element of this list, or
567     * <tt>null</tt> if this list is empty.
568 dl 1.17 *
569 dl 1.19 * @return the last element of this list, or <tt>null</tt> if
570     * this list is empty
571 dl 1.17 * @since 1.6
572     */
573     public E pollLast() {
574     if (size==0)
575     return null;
576     return removeLast();
577     }
578    
579     /**
580 dl 1.19 * Pushes an element onto the stack represented by this list. In other
581 dl 1.20 * words, inserts the element to the front of this list.
582 dl 1.17 *
583     * <p>This method is equivalent to {@link #addFirst}.
584     *
585 dl 1.21 * @param o the element to push
586 dl 1.17 * @since 1.6
587     */
588 dl 1.21 public void push(E o) {
589     addFirst(o);
590 dl 1.17 }
591    
592     /**
593 dl 1.19 * Pops an element from the stack represented by this list. In other
594 dl 1.20 * words, removes and returns the first element of this list.
595 dl 1.17 *
596     * <p>This method is equivalent to {@link #removeFirst()}.
597     *
598 dl 1.19 * @return the element at the front of this list (which is the top
599     * of the stack represented by this list)
600     * @throws NoSuchElementException if this list is empty
601 dl 1.17 * @since 1.6
602     */
603     public E pop() {
604     return removeFirst();
605     }
606    
607     /**
608     * Removes the first occurrence of the specified element in this
609 dl 1.19 * list (when traversing the list from head to tail). If the list
610 dl 1.17 * does not contain the element, it is unchanged.
611     *
612 dl 1.21 * @param o element to be removed from this list, if present
613 dl 1.19 * @return <tt>true</tt> if the list contained the specified element
614 dl 1.17 * @since 1.6
615     */
616 dl 1.21 public boolean removeFirstOccurrence(Object o) {
617     return remove(o);
618 dl 1.17 }
619    
620     /**
621     * Removes the last occurrence of the specified element in this
622 dl 1.19 * list (when traversing the list from head to tail). If the list
623 dl 1.17 * does not contain the element, it is unchanged.
624     *
625 dl 1.19 * @param o element to be removed from this list, if present
626     * @return <tt>true</tt> if the list contained the specified element
627 dl 1.17 * @since 1.6
628     */
629     public boolean removeLastOccurrence(Object o) {
630     if (o==null) {
631     for (Entry e = header.previous; e != header; e = e.previous) {
632     if (e.element==null) {
633     remove(e);
634     return true;
635     }
636     }
637     } else {
638     for (Entry e = header.previous; e != header; e = e.previous) {
639     if (o.equals(e.element)) {
640     remove(e);
641     return true;
642     }
643     }
644     }
645     return false;
646     }
647    
648 tim 1.1 /**
649     * Returns a list-iterator of the elements in this list (in proper
650     * sequence), starting at the specified position in the list.
651     * Obeys the general contract of <tt>List.listIterator(int)</tt>.<p>
652     *
653     * The list-iterator is <i>fail-fast</i>: if the list is structurally
654     * modified at any time after the Iterator is created, in any way except
655     * through the list-iterator's own <tt>remove</tt> or <tt>add</tt>
656     * methods, the list-iterator will throw a
657     * <tt>ConcurrentModificationException</tt>. Thus, in the face of
658     * concurrent modification, the iterator fails quickly and cleanly, rather
659     * than risking arbitrary, non-deterministic behavior at an undetermined
660     * time in the future.
661     *
662     * @param index index of first element to be returned from the
663 jsr166 1.14 * list-iterator (by a call to <tt>next</tt>).
664 tim 1.1 * @return a ListIterator of the elements in this list (in proper
665 jsr166 1.14 * sequence), starting at the specified position in the list.
666 tim 1.1 * @throws IndexOutOfBoundsException if index is out of range
667 jsr166 1.14 * (<tt>index &lt; 0 || index &gt; size()</tt>).
668 dl 1.3 * @see List#listIterator(int)
669 tim 1.1 */
670 dl 1.3 public ListIterator<E> listIterator(int index) {
671 jsr166 1.14 return new ListItr(index);
672 tim 1.1 }
673    
674 dl 1.3 private class ListItr implements ListIterator<E> {
675 jsr166 1.14 private Entry<E> lastReturned = header;
676     private Entry<E> next;
677     private int nextIndex;
678     private int expectedModCount = modCount;
679    
680     ListItr(int index) {
681     if (index < 0 || index > size)
682     throw new IndexOutOfBoundsException("Index: "+index+
683     ", Size: "+size);
684     if (index < (size >> 1)) {
685     next = header.next;
686     for (nextIndex=0; nextIndex<index; nextIndex++)
687     next = next.next;
688     } else {
689     next = header;
690     for (nextIndex=size; nextIndex>index; nextIndex--)
691     next = next.previous;
692     }
693     }
694    
695     public boolean hasNext() {
696     return nextIndex != size;
697     }
698    
699     public E next() {
700     checkForComodification();
701     if (nextIndex == size)
702     throw new NoSuchElementException();
703    
704     lastReturned = next;
705     next = next.next;
706     nextIndex++;
707     return lastReturned.element;
708     }
709    
710     public boolean hasPrevious() {
711     return nextIndex != 0;
712     }
713    
714     public E previous() {
715     if (nextIndex == 0)
716     throw new NoSuchElementException();
717    
718     lastReturned = next = next.previous;
719     nextIndex--;
720     checkForComodification();
721     return lastReturned.element;
722     }
723    
724     public int nextIndex() {
725     return nextIndex;
726     }
727    
728     public int previousIndex() {
729     return nextIndex-1;
730     }
731 jozart 1.12
732 jsr166 1.14 public void remove() {
733 tim 1.1 checkForComodification();
734 jsr166 1.14 Entry<E> lastNext = lastReturned.next;
735 tim 1.1 try {
736     LinkedList.this.remove(lastReturned);
737     } catch (NoSuchElementException e) {
738     throw new IllegalStateException();
739     }
740 jsr166 1.14 if (next==lastReturned)
741     next = lastNext;
742 tim 1.1 else
743 jsr166 1.14 nextIndex--;
744     lastReturned = header;
745     expectedModCount++;
746     }
747    
748     public void set(E o) {
749     if (lastReturned == header)
750     throw new IllegalStateException();
751     checkForComodification();
752     lastReturned.element = o;
753     }
754    
755     public void add(E o) {
756     checkForComodification();
757     lastReturned = header;
758     addBefore(o, next);
759     nextIndex++;
760     expectedModCount++;
761     }
762    
763     final void checkForComodification() {
764     if (modCount != expectedModCount)
765     throw new ConcurrentModificationException();
766     }
767 dl 1.3 }
768    
769     private static class Entry<E> {
770 jsr166 1.14 E element;
771     Entry<E> next;
772     Entry<E> previous;
773    
774     Entry(E element, Entry<E> next, Entry<E> previous) {
775     this.element = element;
776     this.next = next;
777     this.previous = previous;
778     }
779 dl 1.3 }
780    
781     private Entry<E> addBefore(E o, Entry<E> e) {
782 jsr166 1.14 Entry<E> newEntry = new Entry<E>(o, e, e.previous);
783     newEntry.previous.next = newEntry;
784     newEntry.next.previous = newEntry;
785     size++;
786     modCount++;
787     return newEntry;
788     }
789    
790     private E remove(Entry<E> e) {
791     if (e == header)
792     throw new NoSuchElementException();
793    
794     E result = e.element;
795     e.previous.next = e.next;
796     e.next.previous = e.previous;
797     e.next = e.previous = null;
798     e.element = null;
799     size--;
800     modCount++;
801     return result;
802 tim 1.1 }
803    
804     /**
805     * Returns a shallow copy of this <tt>LinkedList</tt>. (The elements
806     * themselves are not cloned.)
807     *
808     * @return a shallow copy of this <tt>LinkedList</tt> instance.
809     */
810     public Object clone() {
811 dl 1.3 LinkedList<E> clone = null;
812 jsr166 1.14 try {
813     clone = (LinkedList<E>) super.clone();
814     } catch (CloneNotSupportedException e) {
815     throw new InternalError();
816     }
817 tim 1.1
818     // Put clone into "virgin" state
819 dl 1.3 clone.header = new Entry<E>(null, null, null);
820 tim 1.1 clone.header.next = clone.header.previous = clone.header;
821     clone.size = 0;
822     clone.modCount = 0;
823    
824     // Initialize clone with our elements
825 dl 1.3 for (Entry<E> e = header.next; e != header; e = e.next)
826 tim 1.1 clone.add(e.element);
827    
828     return clone;
829     }
830    
831     /**
832     * Returns an array containing all of the elements in this list
833     * in the correct order.
834     *
835     * @return an array containing all of the elements in this list
836 jsr166 1.14 * in the correct order.
837 tim 1.1 */
838     public Object[] toArray() {
839 jsr166 1.14 Object[] result = new Object[size];
840 tim 1.1 int i = 0;
841 dl 1.3 for (Entry<E> e = header.next; e != header; e = e.next)
842 tim 1.1 result[i++] = e.element;
843 jsr166 1.14 return result;
844 tim 1.1 }
845    
846     /**
847     * Returns an array containing all of the elements in this list in
848     * the correct order; the runtime type of the returned array is that of
849     * the specified array. If the list fits in the specified array, it
850     * is returned therein. Otherwise, a new array is allocated with the
851     * runtime type of the specified array and the size of this list.<p>
852     *
853     * If the list fits in the specified array with room to spare
854     * (i.e., the array has more elements than the list),
855     * the element in the array immediately following the end of the
856     * collection is set to null. This is useful in determining the length
857     * of the list <i>only</i> if the caller knows that the list
858     * does not contain any null elements.
859     *
860     * @param a the array into which the elements of the list are to
861 jsr166 1.14 * be stored, if it is big enough; otherwise, a new array of the
862     * same runtime type is allocated for this purpose.
863 tim 1.1 * @return an array containing the elements of the list.
864     * @throws ArrayStoreException if the runtime type of a is not a
865     * supertype of the runtime type of every element in this list.
866     * @throws NullPointerException if the specified array is null.
867     */
868 dl 1.3 public <T> T[] toArray(T[] a) {
869 tim 1.1 if (a.length < size)
870 dl 1.3 a = (T[])java.lang.reflect.Array.newInstance(
871 tim 1.1 a.getClass().getComponentType(), size);
872     int i = 0;
873 jsr166 1.14 Object[] result = a;
874 dl 1.3 for (Entry<E> e = header.next; e != header; e = e.next)
875     result[i++] = e.element;
876 tim 1.1
877     if (a.length > size)
878     a[size] = null;
879    
880     return a;
881     }
882    
883     private static final long serialVersionUID = 876323262645176354L;
884    
885     /**
886     * Save the state of this <tt>LinkedList</tt> instance to a stream (that
887     * is, serialize it).
888     *
889     * @serialData The size of the list (the number of elements it
890 jsr166 1.14 * contains) is emitted (int), followed by all of its
891 dl 1.3 * elements (each an Object) in the proper order.
892 tim 1.1 */
893 dl 1.3 private void writeObject(java.io.ObjectOutputStream s)
894 tim 1.1 throws java.io.IOException {
895 jsr166 1.14 // Write out any hidden serialization magic
896     s.defaultWriteObject();
897 tim 1.1
898     // Write out size
899     s.writeInt(size);
900    
901 jsr166 1.14 // Write out all elements in the proper order.
902 tim 1.1 for (Entry e = header.next; e != header; e = e.next)
903     s.writeObject(e.element);
904     }
905    
906     /**
907     * Reconstitute this <tt>LinkedList</tt> instance from a stream (that is
908     * deserialize it).
909     */
910 dl 1.3 private void readObject(java.io.ObjectInputStream s)
911 tim 1.1 throws java.io.IOException, ClassNotFoundException {
912 jsr166 1.14 // Read in any hidden serialization magic
913     s.defaultReadObject();
914 tim 1.1
915     // Read in size
916     int size = s.readInt();
917    
918     // Initialize header
919 dl 1.3 header = new Entry<E>(null, null, null);
920 tim 1.1 header.next = header.previous = header;
921    
922 jsr166 1.14 // Read in all elements in the proper order.
923     for (int i=0; i<size; i++)
924 dl 1.3 addBefore((E)s.readObject(), header);
925 tim 1.1 }
926     }