ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/LinkedList.java
Revision: 1.1
Committed: Wed May 14 21:30:44 2003 UTC (21 years ago) by tim
Branch: MAIN
CVS Tags: JSR166_CR1, JSR166_PRELIMINARY_TEST_RELEASE_1, JSR166_PRELIMINARY_TEST_RELEASE_2, JSR166_PRERELEASE_0_1
Log Message:
Moved main source rooted at . to ./src/main
Moved test source rooted at ./etc/testcases to ./src/test

File Contents

# Content
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 if (numNew==0)
261 return false;
262 modCount++;
263
264 Entry successor = (index==size ? header : entry(index));
265 Entry predecessor = successor.previous;
266 Iterator it = c.iterator();
267 for (int i=0; i<numNew; i++) {
268 Entry e = new Entry(it.next(), successor, predecessor);
269 predecessor.next = e;
270 predecessor = e;
271 }
272 successor.previous = predecessor;
273
274 size += numNew;
275 return true;
276 }
277
278 /**
279 * Removes all of the elements from this list.
280 */
281 public void clear() {
282 modCount++;
283 header.next = header.previous = header;
284 size = 0;
285 }
286
287
288 // Positional Access Operations
289
290 /**
291 * Returns the element at the specified position in this list.
292 *
293 * @param index index of element to return.
294 * @return the element at the specified position in this list.
295 *
296 * @throws IndexOutOfBoundsException if the specified index is is out of
297 * range (<tt>index &lt; 0 || index &gt;= size()</tt>).
298 */
299 public Object get(int index) {
300 return entry(index).element;
301 }
302
303 /**
304 * Replaces the element at the specified position in this list with the
305 * specified element.
306 *
307 * @param index index of element to replace.
308 * @param element element to be stored at the specified position.
309 * @return the element previously at the specified position.
310 * @throws IndexOutOfBoundsException if the specified index is out of
311 * range (<tt>index &lt; 0 || index &gt;= size()</tt>).
312 */
313 public Object set(int index, Object element) {
314 Entry e = entry(index);
315 Object oldVal = e.element;
316 e.element = element;
317 return oldVal;
318 }
319
320 /**
321 * Inserts the specified element at the specified position in this list.
322 * Shifts the element currently at that position (if any) and any
323 * subsequent elements to the right (adds one to their indices).
324 *
325 * @param index index at which the specified element is to be inserted.
326 * @param element element to be inserted.
327 *
328 * @throws IndexOutOfBoundsException if the specified index is out of
329 * range (<tt>index &lt; 0 || index &gt; size()</tt>).
330 */
331 public void add(int index, Object element) {
332 addBefore(element, (index==size ? header : entry(index)));
333 }
334
335 /**
336 * Removes the element at the specified position in this list. Shifts any
337 * subsequent elements to the left (subtracts one from their indices).
338 * Returns the element that was removed from the list.
339 *
340 * @param index the index of the element to removed.
341 * @return the element previously at the specified position.
342 *
343 * @throws IndexOutOfBoundsException if the specified index is out of
344 * range (<tt>index &lt; 0 || index &gt;= size()</tt>).
345 */
346 public Object remove(int index) {
347 Entry e = entry(index);
348 remove(e);
349 return e.element;
350 }
351
352 /**
353 * Return the indexed entry.
354 */
355 private Entry entry(int index) {
356 if (index < 0 || index >= size)
357 throw new IndexOutOfBoundsException("Index: "+index+
358 ", Size: "+size);
359 Entry e = header;
360 if (index < (size >> 1)) {
361 for (int i = 0; i <= index; i++)
362 e = e.next;
363 } else {
364 for (int i = size; i > index; i--)
365 e = e.previous;
366 }
367 return e;
368 }
369
370
371 // Search Operations
372
373 /**
374 * Returns the index in this list of the first occurrence of the
375 * specified element, or -1 if the List does not contain this
376 * element. More formally, returns the lowest index i such that
377 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, or -1 if
378 * there is no such index.
379 *
380 * @param o element to search for.
381 * @return the index in this list of the first occurrence of the
382 * specified element, or -1 if the list does not contain this
383 * element.
384 */
385 public int indexOf(Object o) {
386 int index = 0;
387 if (o==null) {
388 for (Entry e = header.next; e != header; e = e.next) {
389 if (e.element==null)
390 return index;
391 index++;
392 }
393 } else {
394 for (Entry e = header.next; e != header; e = e.next) {
395 if (o.equals(e.element))
396 return index;
397 index++;
398 }
399 }
400 return -1;
401 }
402
403 /**
404 * Returns the index in this list of the last occurrence of the
405 * specified element, or -1 if the list does not contain this
406 * element. More formally, returns the highest index i such that
407 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, or -1 if
408 * there is no such index.
409 *
410 * @param o element to search for.
411 * @return the index in this list of the last occurrence of the
412 * specified element, or -1 if the list does not contain this
413 * element.
414 */
415 public int lastIndexOf(Object o) {
416 int index = size;
417 if (o==null) {
418 for (Entry e = header.previous; e != header; e = e.previous) {
419 index--;
420 if (e.element==null)
421 return index;
422 }
423 } else {
424 for (Entry e = header.previous; e != header; e = e.previous) {
425 index--;
426 if (o.equals(e.element))
427 return index;
428 }
429 }
430 return -1;
431 }
432
433 /**
434 * Returns a list-iterator of the elements in this list (in proper
435 * sequence), starting at the specified position in the list.
436 * Obeys the general contract of <tt>List.listIterator(int)</tt>.<p>
437 *
438 * The list-iterator is <i>fail-fast</i>: if the list is structurally
439 * modified at any time after the Iterator is created, in any way except
440 * through the list-iterator's own <tt>remove</tt> or <tt>add</tt>
441 * methods, the list-iterator will throw a
442 * <tt>ConcurrentModificationException</tt>. Thus, in the face of
443 * concurrent modification, the iterator fails quickly and cleanly, rather
444 * than risking arbitrary, non-deterministic behavior at an undetermined
445 * time in the future.
446 *
447 * @param index index of first element to be returned from the
448 * list-iterator (by a call to <tt>next</tt>).
449 * @return a ListIterator of the elements in this list (in proper
450 * sequence), starting at the specified position in the list.
451 * @throws IndexOutOfBoundsException if index is out of range
452 * (<tt>index &lt; 0 || index &gt; size()</tt>).
453 * @see java.util.List#listIterator(int)
454 */
455 public ListIterator listIterator(int index) {
456 return new ListItr(index);
457 }
458
459 private class ListItr implements ListIterator {
460 private Entry lastReturned = header;
461 private Entry next;
462 private int nextIndex;
463 private int expectedModCount = modCount;
464
465 ListItr(int index) {
466 if (index < 0 || index > size)
467 throw new IndexOutOfBoundsException("Index: "+index+
468 ", Size: "+size);
469 if (index < (size >> 1)) {
470 next = header.next;
471 for (nextIndex=0; nextIndex<index; nextIndex++)
472 next = next.next;
473 } else {
474 next = header;
475 for (nextIndex=size; nextIndex>index; nextIndex--)
476 next = next.previous;
477 }
478 }
479
480 public boolean hasNext() {
481 return nextIndex != size;
482 }
483
484 public Object next() {
485 checkForComodification();
486 if (nextIndex == size)
487 throw new NoSuchElementException();
488
489 lastReturned = next;
490 next = next.next;
491 nextIndex++;
492 return lastReturned.element;
493 }
494
495 public boolean hasPrevious() {
496 return nextIndex != 0;
497 }
498
499 public Object previous() {
500 if (nextIndex == 0)
501 throw new NoSuchElementException();
502
503 lastReturned = next = next.previous;
504 nextIndex--;
505 checkForComodification();
506 return lastReturned.element;
507 }
508
509 public int nextIndex() {
510 return nextIndex;
511 }
512
513 public int previousIndex() {
514 return nextIndex-1;
515 }
516
517 public void remove() {
518 checkForComodification();
519 try {
520 LinkedList.this.remove(lastReturned);
521 } catch (NoSuchElementException e) {
522 throw new IllegalStateException();
523 }
524 if (next==lastReturned)
525 next = lastReturned.next;
526 else
527 nextIndex--;
528 lastReturned = header;
529 expectedModCount++;
530 }
531
532 public void set(Object o) {
533 if (lastReturned == header)
534 throw new IllegalStateException();
535 checkForComodification();
536 lastReturned.element = o;
537 }
538
539 public void add(Object o) {
540 checkForComodification();
541 lastReturned = header;
542 addBefore(o, next);
543 nextIndex++;
544 expectedModCount++;
545 }
546
547 final void checkForComodification() {
548 if (modCount != expectedModCount)
549 throw new ConcurrentModificationException();
550 }
551 }
552
553 private static class Entry {
554 Object element;
555 Entry next;
556 Entry previous;
557
558 Entry(Object element, Entry next, Entry previous) {
559 this.element = element;
560 this.next = next;
561 this.previous = previous;
562 }
563 }
564
565 private Entry addBefore(Object o, Entry e) {
566 Entry newEntry = new Entry(o, e, e.previous);
567 newEntry.previous.next = newEntry;
568 newEntry.next.previous = newEntry;
569 size++;
570 modCount++;
571 return newEntry;
572 }
573
574 private void remove(Entry e) {
575 if (e == header)
576 throw new NoSuchElementException();
577
578 e.previous.next = e.next;
579 e.next.previous = e.previous;
580 size--;
581 modCount++;
582 }
583
584 /**
585 * Returns a shallow copy of this <tt>LinkedList</tt>. (The elements
586 * themselves are not cloned.)
587 *
588 * @return a shallow copy of this <tt>LinkedList</tt> instance.
589 */
590 public Object clone() {
591 LinkedList clone = null;
592 try {
593 clone = (LinkedList)super.clone();
594 } catch (CloneNotSupportedException e) {
595 throw new InternalError();
596 }
597
598 // Put clone into "virgin" state
599 clone.header = new Entry(null, null, null);
600 clone.header.next = clone.header.previous = clone.header;
601 clone.size = 0;
602 clone.modCount = 0;
603
604 // Initialize clone with our elements
605 for (Entry e = header.next; e != header; e = e.next)
606 clone.add(e.element);
607
608 return clone;
609 }
610
611 /**
612 * Returns an array containing all of the elements in this list
613 * in the correct order.
614 *
615 * @return an array containing all of the elements in this list
616 * in the correct order.
617 */
618 public Object[] toArray() {
619 Object[] result = new Object[size];
620 int i = 0;
621 for (Entry e = header.next; e != header; e = e.next)
622 result[i++] = e.element;
623 return result;
624 }
625
626 /**
627 * Returns an array containing all of the elements in this list in
628 * the correct order; the runtime type of the returned array is that of
629 * the specified array. If the list fits in the specified array, it
630 * is returned therein. Otherwise, a new array is allocated with the
631 * runtime type of the specified array and the size of this list.<p>
632 *
633 * If the list fits in the specified array with room to spare
634 * (i.e., the array has more elements than the list),
635 * the element in the array immediately following the end of the
636 * collection is set to null. This is useful in determining the length
637 * of the list <i>only</i> if the caller knows that the list
638 * does not contain any null elements.
639 *
640 * @param a the array into which the elements of the list are to
641 * be stored, if it is big enough; otherwise, a new array of the
642 * same runtime type is allocated for this purpose.
643 * @return an array containing the elements of the list.
644 * @throws ArrayStoreException if the runtime type of a is not a
645 * supertype of the runtime type of every element in this list.
646 * @throws NullPointerException if the specified array is null.
647 */
648 public Object[] toArray(Object a[]) {
649 if (a.length < size)
650 a = (Object[])java.lang.reflect.Array.newInstance(
651 a.getClass().getComponentType(), size);
652 int i = 0;
653 for (Entry e = header.next; e != header; e = e.next)
654 a[i++] = e.element;
655
656 if (a.length > size)
657 a[size] = null;
658
659 return a;
660 }
661
662 private static final long serialVersionUID = 876323262645176354L;
663
664 /**
665 * Save the state of this <tt>LinkedList</tt> instance to a stream (that
666 * is, serialize it).
667 *
668 * @serialData The size of the list (the number of elements it
669 * contains) is emitted (int), followed by all of its
670 * elements (each an Object) in the proper order.
671 */
672 private synchronized void writeObject(java.io.ObjectOutputStream s)
673 throws java.io.IOException {
674 // Write out any hidden serialization magic
675 s.defaultWriteObject();
676
677 // Write out size
678 s.writeInt(size);
679
680 // Write out all elements in the proper order.
681 for (Entry e = header.next; e != header; e = e.next)
682 s.writeObject(e.element);
683 }
684
685 /**
686 * Reconstitute this <tt>LinkedList</tt> instance from a stream (that is
687 * deserialize it).
688 */
689 private synchronized void readObject(java.io.ObjectInputStream s)
690 throws java.io.IOException, ClassNotFoundException {
691 // Read in any hidden serialization magic
692 s.defaultReadObject();
693
694 // Read in size
695 int size = s.readInt();
696
697 // Initialize header
698 header = new Entry(null, null, null);
699 header.next = header.previous = header;
700
701 // Read in all elements in the proper order.
702 for (int i=0; i<size; i++)
703 add(s.readObject());
704 }
705
706 public Object peek() {
707 if (size==0)
708 return null;
709 return header.previous.element;
710 }
711
712 public Object element() {
713 if (size==0)
714 throw new NoSuchElementException();
715 return header.previous.element;
716 }
717
718 public Object poll() {
719 if (size==0)
720 return null;
721 Object last = header.previous.element;
722 remove(header.previous);
723 return last;
724 }
725
726 public Object remove() {
727 if (size==0)
728 throw new NoSuchElementException();
729 Object last = header.previous.element;
730 remove(header.previous);
731 return last;
732 }
733
734 public boolean offer(Object x) {
735 return add(x);
736 }
737
738 }