ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/LinkedList.java
Revision: 1.2
Committed: Thu Aug 7 15:59:46 2003 UTC (20 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.1: +10 -14 lines
Log Message:
Make queue ops match sense of first/last

File Contents

# User Rev Content
1 tim 1.1 /*
2     * @(#)LinkedList.java 1.43 01/12/03
3     *
4     * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
5     * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6     */
7    
8     package java.util;
9    
10     /**
11     * <b>JSR166: Added Queue operations</b>.<p>
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     * used as a stack, queue, or double-ended queue (deque).<p>
19     *
20     * All of the stack/queue/deque operations could be easily recast in terms of
21     * the standard list operations. They're included here primarily for
22     * convenience, though they may run slightly faster than the equivalent List
23     * operations.<p>
24     *
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     * the begining or the end, whichever is closer to the specified index.<p>
28     *
29     * <b>Note that this implementation is not synchronized.</b> If multiple
30     * threads access a list concurrently, and at least one of the threads
31     * modifies the list structurally, it <i>must</i> be synchronized
32     * externally. (A structural modification is any operation that adds or
33     * deletes one or more elements; merely setting the value of an element is not
34     * a structural modification.) This is typically accomplished by
35     * synchronizing on some object that naturally encapsulates the list. If no
36     * such object exists, the list should be "wrapped" using the
37     * Collections.synchronizedList method. This is best done at creation time,
38     * to prevent accidental unsynchronized access to the list: <pre>
39     * List list = Collections.synchronizedList(new LinkedList(...));
40     * </pre><p>
41     *
42     * The iterators returned by the this class's <tt>iterator</tt> and
43     * <tt>listIterator</tt> methods are <i>fail-fast</i>: if the list is
44     * structurally modified at any time after the iterator is created, in any way
45     * except through the Iterator's own <tt>remove</tt> or <tt>add</tt> methods,
46     * the iterator will throw a <tt>ConcurrentModificationException</tt>. Thus,
47     * in the face of concurrent modification, the iterator fails quickly and
48     * cleanly, rather than risking arbitrary, non-deterministic behavior at an
49     * undetermined time in the future.
50     *
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     * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
55     * 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     * should be used only to detect bugs.</i>
58     *
59     * @author Josh Bloch
60     * @version 1.43, 12/03/01
61     * @see java.util.List
62     * @see java.util.ArrayList
63     * @see java.util.Vector
64     * @see java.util.Collections#synchronizedList(java.util.List)
65     * @since 1.2
66     */
67    
68     public class LinkedList extends AbstractSequentialList
69     implements List, Queue, Cloneable, java.io.Serializable
70     {
71     private transient Entry header = new Entry(null, null, null);
72     private transient int size = 0;
73    
74     /**
75     * Constructs an empty list.
76     */
77     public LinkedList() {
78     header.next = header.previous = header;
79     }
80    
81     /**
82     * Constructs a list containing the elements of the specified
83     * collection, in the order they are returned by the collection's
84     * iterator.
85     *
86     * @param c the collection whose elements are to be placed into this list.
87     * @throws NullPointerException if the specified collection is null.
88     */
89     public LinkedList(Collection c) {
90     this();
91     addAll(c);
92     }
93    
94     /**
95     * Returns the first element in this list.
96     *
97     * @return the first element in this list.
98     * @throws NoSuchElementException if this list is empty.
99     */
100     public Object getFirst() {
101     if (size==0)
102     throw new NoSuchElementException();
103    
104     return header.next.element;
105     }
106    
107     /**
108     * Returns the last element in this list.
109     *
110     * @return the last element in this list.
111     * @throws NoSuchElementException if this list is empty.
112     */
113     public Object getLast() {
114     if (size==0)
115     throw new NoSuchElementException();
116    
117     return header.previous.element;
118     }
119    
120     /**
121     * Removes and returns the first element from this list.
122     *
123     * @return the first element from this list.
124     * @throws NoSuchElementException if this list is empty.
125     */
126     public Object removeFirst() {
127     Object first = header.next.element;
128     remove(header.next);
129     return first;
130     }
131    
132     /**
133     * Removes and returns the last element from this list.
134     *
135     * @return the last element from this list.
136     * @throws NoSuchElementException if this list is empty.
137     */
138     public Object removeLast() {
139     Object last = header.previous.element;
140     remove(header.previous);
141     return last;
142     }
143    
144     /**
145     * Inserts the given element at the beginning of this list.
146     *
147     * @param o the element to be inserted at the beginning of this list.
148     */
149     public void addFirst(Object o) {
150     addBefore(o, header.next);
151     }
152    
153     /**
154     * Appends the given element to the end of this list. (Identical in
155     * function to the <tt>add</tt> method; included only for consistency.)
156     *
157     * @param o the element to be inserted at the end of this list.
158     */
159     public void addLast(Object o) {
160     addBefore(o, header);
161     }
162    
163     /**
164     * Returns <tt>true</tt> if this list contains the specified element.
165     * More formally, returns <tt>true</tt> if and only if this list contains
166     * at least one element <tt>e</tt> such that <tt>(o==null ? e==null
167     * : o.equals(e))</tt>.
168     *
169     * @param o element whose presence in this list is to be tested.
170     * @return <tt>true</tt> if this list contains the specified element.
171     */
172     public boolean contains(Object o) {
173     return indexOf(o) != -1;
174     }
175    
176     /**
177     * Returns the number of elements in this list.
178     *
179     * @return the number of elements in this list.
180     */
181     public int size() {
182     return size;
183     }
184    
185     /**
186     * Appends the specified element to the end of this list.
187     *
188     * @param o element to be appended to this list.
189     * @return <tt>true</tt> (as per the general contract of
190     * <tt>Collection.add</tt>).
191     */
192     public boolean add(Object o) {
193     addBefore(o, header);
194     return true;
195     }
196    
197     /**
198     * Removes the first occurrence of the specified element in this list. If
199     * the list does not contain the element, it is unchanged. More formally,
200     * removes the element with the lowest index <tt>i</tt> such that
201     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt> (if such an
202     * element exists).
203     *
204     * @param o element to be removed from this list, if present.
205     * @return <tt>true</tt> if the list contained the specified element.
206     */
207     public boolean remove(Object o) {
208     if (o==null) {
209     for (Entry e = header.next; e != header; e = e.next) {
210     if (e.element==null) {
211     remove(e);
212     return true;
213     }
214     }
215     } else {
216     for (Entry e = header.next; e != header; e = e.next) {
217     if (o.equals(e.element)) {
218     remove(e);
219     return true;
220     }
221     }
222     }
223     return false;
224     }
225    
226     /**
227     * Appends all of the elements in the specified collection to the end of
228     * this list, in the order that they are returned by the specified
229     * collection's iterator. The behavior of this operation is undefined if
230     * the specified collection is modified while the operation is in
231     * progress. (This implies that the behavior of this call is undefined if
232     * the specified Collection is this list, and this list is nonempty.)
233     *
234     * @param c the elements to be inserted into this list.
235     * @return <tt>true</tt> if this list changed as a result of the call.
236     * @throws NullPointerException if the specified collection is null.
237     */
238     public boolean addAll(Collection c) {
239     return addAll(size, c);
240     }
241    
242     /**
243     * Inserts all of the elements in the specified collection into this
244     * list, starting at the specified position. Shifts the element
245     * currently at that position (if any) and any subsequent elements to
246     * the right (increases their indices). The new elements will appear
247     * in the list in the order that they are returned by the
248     * specified collection's iterator.
249     *
250     * @param index index at which to insert first element
251     * from the specified collection.
252     * @param c elements to be inserted into this list.
253     * @return <tt>true</tt> if this list changed as a result of the call.
254     * @throws IndexOutOfBoundsException if the specified index is out of
255     * range (<tt>index &lt; 0 || index &gt; size()</tt>).
256     * @throws NullPointerException if the specified collection is null.
257     */
258     public boolean addAll(int index, Collection c) {
259     int numNew = c.size();
260 dl 1.2 if (numNew==0) {
261     if (index < 0 || index >= size)
262     throw new IndexOutOfBoundsException();
263     else
264     return false;
265     }
266 tim 1.1 modCount++;
267    
268     Entry successor = (index==size ? header : entry(index));
269     Entry predecessor = successor.previous;
270     Iterator it = c.iterator();
271     for (int i=0; i<numNew; i++) {
272     Entry e = new Entry(it.next(), successor, predecessor);
273     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     modCount++;
287     header.next = header.previous = header;
288     size = 0;
289     }
290    
291    
292     // Positional Access Operations
293    
294     /**
295     * Returns the element at the specified position in this list.
296     *
297     * @param index index of element to return.
298     * @return the element at the specified position in this list.
299     *
300     * @throws IndexOutOfBoundsException if the specified index is is out of
301     * range (<tt>index &lt; 0 || index &gt;= size()</tt>).
302     */
303     public Object get(int index) {
304     return entry(index).element;
305     }
306    
307     /**
308     * Replaces the element at the specified position in this list with the
309     * specified element.
310     *
311     * @param index index of element to replace.
312     * @param element element to be stored at the specified position.
313     * @return the element previously at the specified position.
314     * @throws IndexOutOfBoundsException if the specified index is out of
315     * range (<tt>index &lt; 0 || index &gt;= size()</tt>).
316     */
317     public Object set(int index, Object element) {
318     Entry e = entry(index);
319     Object oldVal = e.element;
320     e.element = element;
321     return oldVal;
322     }
323    
324     /**
325     * Inserts the specified element at the specified position in this list.
326     * Shifts the element currently at that position (if any) and any
327     * subsequent elements to the right (adds one to their indices).
328     *
329     * @param index index at which the specified element is to be inserted.
330     * @param element element to be inserted.
331     *
332     * @throws IndexOutOfBoundsException if the specified index is out of
333     * range (<tt>index &lt; 0 || index &gt; size()</tt>).
334     */
335     public void add(int index, Object element) {
336     addBefore(element, (index==size ? header : entry(index)));
337     }
338    
339     /**
340     * Removes the element at the specified position in this list. Shifts any
341     * subsequent elements to the left (subtracts one from their indices).
342     * Returns the element that was removed from the list.
343     *
344     * @param index the index of the element to removed.
345     * @return the element previously at the specified position.
346     *
347     * @throws IndexOutOfBoundsException if the specified index is out of
348     * range (<tt>index &lt; 0 || index &gt;= size()</tt>).
349     */
350     public Object remove(int index) {
351     Entry e = entry(index);
352     remove(e);
353     return e.element;
354     }
355    
356     /**
357     * Return the indexed entry.
358     */
359     private Entry entry(int index) {
360     if (index < 0 || index >= size)
361     throw new IndexOutOfBoundsException("Index: "+index+
362     ", Size: "+size);
363     Entry e = header;
364     if (index < (size >> 1)) {
365     for (int i = 0; i <= index; i++)
366     e = e.next;
367     } else {
368     for (int i = size; i > index; i--)
369     e = e.previous;
370     }
371     return e;
372     }
373    
374    
375     // Search Operations
376    
377     /**
378     * Returns the index in this list of the first occurrence of the
379     * specified element, or -1 if the List does not contain this
380     * element. More formally, returns the lowest index i such that
381     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, or -1 if
382     * there is no such index.
383     *
384     * @param o element to search for.
385     * @return the index in this list of the first occurrence of the
386     * specified element, or -1 if the list does not contain this
387     * element.
388     */
389     public int indexOf(Object o) {
390     int index = 0;
391     if (o==null) {
392     for (Entry e = header.next; e != header; e = e.next) {
393     if (e.element==null)
394     return index;
395     index++;
396     }
397     } else {
398     for (Entry e = header.next; e != header; e = e.next) {
399     if (o.equals(e.element))
400     return index;
401     index++;
402     }
403     }
404     return -1;
405     }
406    
407     /**
408     * Returns the index in this list of the last occurrence of the
409     * specified element, or -1 if the list does not contain this
410     * element. More formally, returns the highest index i such that
411     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, or -1 if
412     * there is no such index.
413     *
414     * @param o element to search for.
415     * @return the index in this list of the last occurrence of the
416     * specified element, or -1 if the list does not contain this
417     * element.
418     */
419     public int lastIndexOf(Object o) {
420     int index = size;
421     if (o==null) {
422     for (Entry e = header.previous; e != header; e = e.previous) {
423     index--;
424     if (e.element==null)
425     return index;
426     }
427     } else {
428     for (Entry e = header.previous; e != header; e = e.previous) {
429     index--;
430     if (o.equals(e.element))
431     return index;
432     }
433     }
434     return -1;
435     }
436    
437     /**
438     * Returns a list-iterator of the elements in this list (in proper
439     * sequence), starting at the specified position in the list.
440     * Obeys the general contract of <tt>List.listIterator(int)</tt>.<p>
441     *
442     * The list-iterator is <i>fail-fast</i>: if the list is structurally
443     * modified at any time after the Iterator is created, in any way except
444     * through the list-iterator's own <tt>remove</tt> or <tt>add</tt>
445     * methods, the list-iterator will throw a
446     * <tt>ConcurrentModificationException</tt>. Thus, in the face of
447     * concurrent modification, the iterator fails quickly and cleanly, rather
448     * than risking arbitrary, non-deterministic behavior at an undetermined
449     * time in the future.
450     *
451     * @param index index of first element to be returned from the
452     * list-iterator (by a call to <tt>next</tt>).
453     * @return a ListIterator of the elements in this list (in proper
454     * sequence), starting at the specified position in the list.
455     * @throws IndexOutOfBoundsException if index is out of range
456     * (<tt>index &lt; 0 || index &gt; size()</tt>).
457     * @see java.util.List#listIterator(int)
458     */
459     public ListIterator listIterator(int index) {
460     return new ListItr(index);
461     }
462    
463     private class ListItr implements ListIterator {
464     private Entry lastReturned = header;
465     private Entry next;
466     private int nextIndex;
467     private int expectedModCount = modCount;
468    
469     ListItr(int index) {
470     if (index < 0 || index > size)
471     throw new IndexOutOfBoundsException("Index: "+index+
472     ", Size: "+size);
473     if (index < (size >> 1)) {
474     next = header.next;
475     for (nextIndex=0; nextIndex<index; nextIndex++)
476     next = next.next;
477     } else {
478     next = header;
479     for (nextIndex=size; nextIndex>index; nextIndex--)
480     next = next.previous;
481     }
482     }
483    
484     public boolean hasNext() {
485     return nextIndex != size;
486     }
487    
488     public Object next() {
489     checkForComodification();
490     if (nextIndex == size)
491     throw new NoSuchElementException();
492    
493     lastReturned = next;
494     next = next.next;
495     nextIndex++;
496     return lastReturned.element;
497     }
498    
499     public boolean hasPrevious() {
500     return nextIndex != 0;
501     }
502    
503     public Object previous() {
504     if (nextIndex == 0)
505     throw new NoSuchElementException();
506    
507     lastReturned = next = next.previous;
508     nextIndex--;
509     checkForComodification();
510     return lastReturned.element;
511     }
512    
513     public int nextIndex() {
514     return nextIndex;
515     }
516    
517     public int previousIndex() {
518     return nextIndex-1;
519     }
520    
521     public void remove() {
522     checkForComodification();
523     try {
524     LinkedList.this.remove(lastReturned);
525     } catch (NoSuchElementException e) {
526     throw new IllegalStateException();
527     }
528     if (next==lastReturned)
529     next = lastReturned.next;
530     else
531     nextIndex--;
532     lastReturned = header;
533     expectedModCount++;
534     }
535    
536     public void set(Object o) {
537     if (lastReturned == header)
538     throw new IllegalStateException();
539     checkForComodification();
540     lastReturned.element = o;
541     }
542    
543     public void add(Object o) {
544     checkForComodification();
545     lastReturned = header;
546     addBefore(o, next);
547     nextIndex++;
548     expectedModCount++;
549     }
550    
551     final void checkForComodification() {
552     if (modCount != expectedModCount)
553     throw new ConcurrentModificationException();
554     }
555     }
556    
557     private static class Entry {
558     Object element;
559     Entry next;
560     Entry previous;
561    
562     Entry(Object element, Entry next, Entry previous) {
563     this.element = element;
564     this.next = next;
565     this.previous = previous;
566     }
567     }
568    
569     private Entry addBefore(Object o, Entry e) {
570     Entry newEntry = new Entry(o, e, e.previous);
571     newEntry.previous.next = newEntry;
572     newEntry.next.previous = newEntry;
573     size++;
574     modCount++;
575     return newEntry;
576     }
577    
578     private void remove(Entry e) {
579     if (e == header)
580     throw new NoSuchElementException();
581    
582     e.previous.next = e.next;
583     e.next.previous = e.previous;
584     size--;
585     modCount++;
586     }
587    
588     /**
589     * Returns a shallow copy of this <tt>LinkedList</tt>. (The elements
590     * themselves are not cloned.)
591     *
592     * @return a shallow copy of this <tt>LinkedList</tt> instance.
593     */
594     public Object clone() {
595     LinkedList clone = null;
596     try {
597     clone = (LinkedList)super.clone();
598     } catch (CloneNotSupportedException e) {
599     throw new InternalError();
600     }
601    
602     // Put clone into "virgin" state
603     clone.header = new Entry(null, null, null);
604     clone.header.next = clone.header.previous = clone.header;
605     clone.size = 0;
606     clone.modCount = 0;
607    
608     // Initialize clone with our elements
609     for (Entry e = header.next; e != header; e = e.next)
610     clone.add(e.element);
611    
612     return clone;
613     }
614    
615     /**
616     * Returns an array containing all of the elements in this list
617     * in the correct order.
618     *
619     * @return an array containing all of the elements in this list
620     * in the correct order.
621     */
622     public Object[] toArray() {
623     Object[] result = new Object[size];
624     int i = 0;
625     for (Entry e = header.next; e != header; e = e.next)
626     result[i++] = e.element;
627     return result;
628     }
629    
630     /**
631     * Returns an array containing all of the elements in this list in
632     * the correct order; the runtime type of the returned array is that of
633     * the specified array. If the list fits in the specified array, it
634     * is returned therein. Otherwise, a new array is allocated with the
635     * runtime type of the specified array and the size of this list.<p>
636     *
637     * If the list fits in the specified array with room to spare
638     * (i.e., the array has more elements than the list),
639     * the element in the array immediately following the end of the
640     * collection is set to null. This is useful in determining the length
641     * of the list <i>only</i> if the caller knows that the list
642     * does not contain any null elements.
643     *
644     * @param a the array into which the elements of the list are to
645     * be stored, if it is big enough; otherwise, a new array of the
646     * same runtime type is allocated for this purpose.
647     * @return an array containing the elements of the list.
648     * @throws ArrayStoreException if the runtime type of a is not a
649     * supertype of the runtime type of every element in this list.
650     * @throws NullPointerException if the specified array is null.
651     */
652     public Object[] toArray(Object a[]) {
653     if (a.length < size)
654     a = (Object[])java.lang.reflect.Array.newInstance(
655     a.getClass().getComponentType(), size);
656     int i = 0;
657     for (Entry e = header.next; e != header; e = e.next)
658     a[i++] = e.element;
659    
660     if (a.length > size)
661     a[size] = null;
662    
663     return a;
664     }
665    
666     private static final long serialVersionUID = 876323262645176354L;
667    
668     /**
669     * Save the state of this <tt>LinkedList</tt> instance to a stream (that
670     * is, serialize it).
671     *
672     * @serialData The size of the list (the number of elements it
673     * contains) is emitted (int), followed by all of its
674     * elements (each an Object) in the proper order.
675     */
676     private synchronized void writeObject(java.io.ObjectOutputStream s)
677     throws java.io.IOException {
678     // Write out any hidden serialization magic
679     s.defaultWriteObject();
680    
681     // Write out size
682     s.writeInt(size);
683    
684     // Write out all elements in the proper order.
685     for (Entry e = header.next; e != header; e = e.next)
686     s.writeObject(e.element);
687     }
688    
689     /**
690     * Reconstitute this <tt>LinkedList</tt> instance from a stream (that is
691     * deserialize it).
692     */
693     private synchronized void readObject(java.io.ObjectInputStream s)
694     throws java.io.IOException, ClassNotFoundException {
695     // Read in any hidden serialization magic
696     s.defaultReadObject();
697    
698     // Read in size
699     int size = s.readInt();
700    
701     // Initialize header
702     header = new Entry(null, null, null);
703     header.next = header.previous = header;
704    
705     // Read in all elements in the proper order.
706     for (int i=0; i<size; i++)
707     add(s.readObject());
708     }
709    
710     public Object peek() {
711     if (size==0)
712     return null;
713 dl 1.2 return getFirst();
714 tim 1.1 }
715    
716     public Object element() {
717 dl 1.2 return getFirst();
718 tim 1.1 }
719    
720     public Object poll() {
721     if (size==0)
722     return null;
723 dl 1.2 return removeFirst();
724 tim 1.1 }
725    
726     public Object remove() {
727 dl 1.2 return removeFirst();
728 tim 1.1 }
729    
730     public boolean offer(Object x) {
731     return add(x);
732     }
733    
734     }