001: /*
002: * @(#)LinkedList.java 1.39 06/10/10
003: *
004: * Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved.
005: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
006: *
007: * This program is free software; you can redistribute it and/or
008: * modify it under the terms of the GNU General Public License version
009: * 2 only, as published by the Free Software Foundation.
010: *
011: * This program is distributed in the hope that it will be useful, but
012: * WITHOUT ANY WARRANTY; without even the implied warranty of
013: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014: * General Public License version 2 for more details (a copy is
015: * included at /legal/license.txt).
016: *
017: * You should have received a copy of the GNU General Public License
018: * version 2 along with this work; if not, write to the Free Software
019: * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
020: * 02110-1301 USA
021: *
022: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
023: * Clara, CA 95054 or visit www.sun.com if you need additional
024: * information or have any questions.
025: *
026: */
027:
028: package java.util;
029:
030: /**
031: * Linked list implementation of the <tt>List</tt> interface. Implements all
032: * optional list operations, and permits all elements (including
033: * <tt>null</tt>). In addition to implementing the <tt>List</tt> interface,
034: * the <tt>LinkedList</tt> class provides uniformly named methods to
035: * <tt>get</tt>, <tt>remove</tt> and <tt>insert</tt> an element at the
036: * beginning and end of the list. These operations allow linked lists to be
037: * used as a stack, queue, or double-ended queue (deque).<p>
038: *
039: * All of the stack/queue/deque operations could be easily recast in terms of
040: * the standard list operations. They're included here primarily for
041: * convenience, though they may run slightly faster than the equivalent List
042: * operations.<p>
043: *
044: * All of the operations perform as could be expected for a doubly-linked
045: * list. Operations that index into the list will traverse the list from
046: * the begining or the end, whichever is closer to the specified index.<p>
047: *
048: * <b>Note that this implementation is not synchronized.</b> If multiple
049: * threads access a list concurrently, and at least one of the threads
050: * modifies the list structurally, it <i>must</i> be synchronized
051: * externally. (A structural modification is any operation that adds or
052: * deletes one or more elements; merely setting the value of an element is not
053: * a structural modification.) This is typically accomplished by
054: * synchronizing on some object that naturally encapsulates the list. If no
055: * such object exists, the list should be "wrapped" using the
056: * Collections.synchronizedList method. This is best done at creation time,
057: * to prevent accidental unsynchronized access to the list: <pre>
058: * List list = Collections.synchronizedList(new LinkedList(...));
059: * </pre><p>
060: *
061: * The iterators returned by the this class's <tt>iterator</tt> and
062: * <tt>listIterator</tt> methods are <i>fail-fast</i>: if the list is
063: * structurally modified at any time after the iterator is created, in any way
064: * except through the Iterator's own <tt>remove</tt> or <tt>add</tt> methods,
065: * the iterator will throw a <tt>ConcurrentModificationException</tt>. Thus,
066: * in the face of concurrent modification, the iterator fails quickly and
067: * cleanly, rather than risking arbitrary, non-deterministic behavior at an
068: * undetermined time in the future.
069: *
070: * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
071: * as it is, generally speaking, impossible to make any hard guarantees in the
072: * presence of unsynchronized concurrent modification. Fail-fast iterators
073: * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
074: * Therefore, it would be wrong to write a program that depended on this
075: * exception for its correctness: <i>the fail-fast behavior of iterators
076: * should be used only to detect bugs.</i><p>
077: *
078: * This class is a member of the
079: * <a href="{@docRoot}/../guide/collections/index.html">
080: * Java Collections Framework</a>.
081: *
082: * @author Josh Bloch
083: * @version 1.39, 10/10/06
084: * @see List
085: * @see ArrayList
086: * @see Vector
087: * @see Collections#synchronizedList(List)
088: * @since 1.2
089: */
090:
091: public class LinkedList extends AbstractSequentialList implements List,
092: Cloneable, java.io.Serializable {
093: private transient Entry header = new Entry(null, null, null);
094: private transient int size = 0;
095:
096: /**
097: * Constructs an empty list.
098: */
099: public LinkedList() {
100: header.next = header.previous = header;
101: }
102:
103: /**
104: * Constructs a list containing the elements of the specified
105: * collection, in the order they are returned by the collection's
106: * iterator.
107: *
108: * @param c the collection whose elements are to be placed into this list.
109: * @throws NullPointerException if the specified collection is null.
110: */
111: public LinkedList(Collection c) {
112: this ();
113: addAll(c);
114: }
115:
116: /**
117: * Returns the first element in this list.
118: *
119: * @return the first element in this list.
120: * @throws NoSuchElementException if this list is empty.
121: */
122: public Object getFirst() {
123: if (size == 0)
124: throw new NoSuchElementException();
125:
126: return header.next.element;
127: }
128:
129: /**
130: * Returns the last element in this list.
131: *
132: * @return the last element in this list.
133: * @throws NoSuchElementException if this list is empty.
134: */
135: public Object getLast() {
136: if (size == 0)
137: throw new NoSuchElementException();
138:
139: return header.previous.element;
140: }
141:
142: /**
143: * Removes and returns the first element from this list.
144: *
145: * @return the first element from this list.
146: * @throws NoSuchElementException if this list is empty.
147: */
148: public Object removeFirst() {
149: Object first = header.next.element;
150: remove(header.next);
151: return first;
152: }
153:
154: /**
155: * Removes and returns the last element from this list.
156: *
157: * @return the last element from this list.
158: * @throws NoSuchElementException if this list is empty.
159: */
160: public Object removeLast() {
161: Object last = header.previous.element;
162: remove(header.previous);
163: return last;
164: }
165:
166: /**
167: * Inserts the given element at the beginning of this list.
168: *
169: * @param o the element to be inserted at the beginning of this list.
170: */
171: public void addFirst(Object o) {
172: addBefore(o, header.next);
173: }
174:
175: /**
176: * Appends the given element to the end of this list. (Identical in
177: * function to the <tt>add</tt> method; included only for consistency.)
178: *
179: * @param o the element to be inserted at the end of this list.
180: */
181: public void addLast(Object o) {
182: addBefore(o, header);
183: }
184:
185: /**
186: * Returns <tt>true</tt> if this list contains the specified element.
187: * More formally, returns <tt>true</tt> if and only if this list contains
188: * at least one element <tt>e</tt> such that <tt>(o==null ? e==null
189: * : o.equals(e))</tt>.
190: *
191: * @param o element whose presence in this list is to be tested.
192: * @return <tt>true</tt> if this list contains the specified element.
193: */
194: public boolean contains(Object o) {
195: return indexOf(o) != -1;
196: }
197:
198: /**
199: * Returns the number of elements in this list.
200: *
201: * @return the number of elements in this list.
202: */
203: public int size() {
204: return size;
205: }
206:
207: /**
208: * Appends the specified element to the end of this list.
209: *
210: * @param o element to be appended to this list.
211: * @return <tt>true</tt> (as per the general contract of
212: * <tt>Collection.add</tt>).
213: */
214: public boolean add(Object o) {
215: addBefore(o, header);
216: return true;
217: }
218:
219: /**
220: * Removes the first occurrence of the specified element in this list. If
221: * the list does not contain the element, it is unchanged. More formally,
222: * removes the element with the lowest index <tt>i</tt> such that
223: * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt> (if such an
224: * element exists).
225: *
226: * @param o element to be removed from this list, if present.
227: * @return <tt>true</tt> if the list contained the specified element.
228: */
229: public boolean remove(Object o) {
230: if (o == null) {
231: for (Entry e = header.next; e != header; e = e.next) {
232: if (e.element == null) {
233: remove(e);
234: return true;
235: }
236: }
237: } else {
238: for (Entry e = header.next; e != header; e = e.next) {
239: if (o.equals(e.element)) {
240: remove(e);
241: return true;
242: }
243: }
244: }
245: return false;
246: }
247:
248: /**
249: * Appends all of the elements in the specified collection to the end of
250: * this list, in the order that they are returned by the specified
251: * collection's iterator. The behavior of this operation is undefined if
252: * the specified collection is modified while the operation is in
253: * progress. (This implies that the behavior of this call is undefined if
254: * the specified Collection is this list, and this list is nonempty.)
255: *
256: * @param c the elements to be inserted into this list.
257: * @return <tt>true</tt> if this list changed as a result of the call.
258: * @throws NullPointerException if the specified collection is null.
259: */
260: public boolean addAll(Collection c) {
261: return addAll(size, c);
262: }
263:
264: /**
265: * Inserts all of the elements in the specified collection into this
266: * list, starting at the specified position. Shifts the element
267: * currently at that position (if any) and any subsequent elements to
268: * the right (increases their indices). The new elements will appear
269: * in the list in the order that they are returned by the
270: * specified collection's iterator.
271: *
272: * @param index index at which to insert first element
273: * from the specified collection.
274: * @param c elements to be inserted into this list.
275: * @return <tt>true</tt> if this list changed as a result of the call.
276: * @throws IndexOutOfBoundsException if the specified index is out of
277: * range (<tt>index < 0 || index > size()</tt>).
278: * @throws NullPointerException if the specified collection is null.
279: */
280: public boolean addAll(int index, Collection c) {
281: Object[] a = c.toArray();
282: int numNew = a.length;
283: if (numNew == 0)
284: return false;
285: modCount++;
286:
287: Entry successor = (index == size ? header : entry(index));
288: Entry predecessor = successor.previous;
289: for (int i = 0; i < numNew; i++) {
290: Entry e = new Entry(a[i], successor, predecessor);
291: predecessor.next = e;
292: predecessor = e;
293: }
294: successor.previous = predecessor;
295:
296: size += numNew;
297: return true;
298: }
299:
300: /**
301: * Removes all of the elements from this list.
302: */
303: public void clear() {
304: modCount++;
305: header.next = header.previous = header;
306: size = 0;
307: }
308:
309: // Positional Access Operations
310:
311: /**
312: * Returns the element at the specified position in this list.
313: *
314: * @param index index of element to return.
315: * @return the element at the specified position in this list.
316: *
317: * @throws IndexOutOfBoundsException if the specified index is is out of
318: * range (<tt>index < 0 || index >= size()</tt>).
319: */
320: public Object get(int index) {
321: return entry(index).element;
322: }
323:
324: /**
325: * Replaces the element at the specified position in this list with the
326: * specified element.
327: *
328: * @param index index of element to replace.
329: * @param element element to be stored at the specified position.
330: * @return the element previously at the specified position.
331: * @throws IndexOutOfBoundsException if the specified index is out of
332: * range (<tt>index < 0 || index >= size()</tt>).
333: */
334: public Object set(int index, Object element) {
335: Entry e = entry(index);
336: Object oldVal = e.element;
337: e.element = element;
338: return oldVal;
339: }
340:
341: /**
342: * Inserts the specified element at the specified position in this list.
343: * Shifts the element currently at that position (if any) and any
344: * subsequent elements to the right (adds one to their indices).
345: *
346: * @param index index at which the specified element is to be inserted.
347: * @param element element to be inserted.
348: *
349: * @throws IndexOutOfBoundsException if the specified index is out of
350: * range (<tt>index < 0 || index > size()</tt>).
351: */
352: public void add(int index, Object element) {
353: addBefore(element, (index == size ? header : entry(index)));
354: }
355:
356: /**
357: * Removes the element at the specified position in this list. Shifts any
358: * subsequent elements to the left (subtracts one from their indices).
359: * Returns the element that was removed from the list.
360: *
361: * @param index the index of the element to removed.
362: * @return the element previously at the specified position.
363: *
364: * @throws IndexOutOfBoundsException if the specified index is out of
365: * range (<tt>index < 0 || index >= size()</tt>).
366: */
367: public Object remove(int index) {
368: Entry e = entry(index);
369: remove(e);
370: return e.element;
371: }
372:
373: /**
374: * Return the indexed entry.
375: */
376: private Entry entry(int index) {
377: if (index < 0 || index >= size)
378: throw new IndexOutOfBoundsException("Index: " + index
379: + ", Size: " + size);
380: Entry e = header;
381: if (index < (size >> 1)) {
382: for (int i = 0; i <= index; i++)
383: e = e.next;
384: } else {
385: for (int i = size; i > index; i--)
386: e = e.previous;
387: }
388: return e;
389: }
390:
391: // Search Operations
392:
393: /**
394: * Returns the index in this list of the first occurrence of the
395: * specified element, or -1 if the List does not contain this
396: * element. More formally, returns the lowest index i such that
397: * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, or -1 if
398: * there is no such index.
399: *
400: * @param o element to search for.
401: * @return the index in this list of the first occurrence of the
402: * specified element, or -1 if the list does not contain this
403: * element.
404: */
405: public int indexOf(Object o) {
406: int index = 0;
407: if (o == null) {
408: for (Entry e = header.next; e != header; e = e.next) {
409: if (e.element == null)
410: return index;
411: index++;
412: }
413: } else {
414: for (Entry e = header.next; e != header; e = e.next) {
415: if (o.equals(e.element))
416: return index;
417: index++;
418: }
419: }
420: return -1;
421: }
422:
423: /**
424: * Returns the index in this list of the last occurrence of the
425: * specified element, or -1 if the list does not contain this
426: * element. More formally, returns the highest index i such that
427: * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>, or -1 if
428: * there is no such index.
429: *
430: * @param o element to search for.
431: * @return the index in this list of the last occurrence of the
432: * specified element, or -1 if the list does not contain this
433: * element.
434: */
435: public int lastIndexOf(Object o) {
436: int index = size;
437: if (o == null) {
438: for (Entry e = header.previous; e != header; e = e.previous) {
439: index--;
440: if (e.element == null)
441: return index;
442: }
443: } else {
444: for (Entry e = header.previous; e != header; e = e.previous) {
445: index--;
446: if (o.equals(e.element))
447: return index;
448: }
449: }
450: return -1;
451: }
452:
453: /**
454: * Returns a list-iterator of the elements in this list (in proper
455: * sequence), starting at the specified position in the list.
456: * Obeys the general contract of <tt>List.listIterator(int)</tt>.<p>
457: *
458: * The list-iterator is <i>fail-fast</i>: if the list is structurally
459: * modified at any time after the Iterator is created, in any way except
460: * through the list-iterator's own <tt>remove</tt> or <tt>add</tt>
461: * methods, the list-iterator will throw a
462: * <tt>ConcurrentModificationException</tt>. Thus, in the face of
463: * concurrent modification, the iterator fails quickly and cleanly, rather
464: * than risking arbitrary, non-deterministic behavior at an undetermined
465: * time in the future.
466: *
467: * @param index index of first element to be returned from the
468: * list-iterator (by a call to <tt>next</tt>).
469: * @return a ListIterator of the elements in this list (in proper
470: * sequence), starting at the specified position in the list.
471: * @throws IndexOutOfBoundsException if index is out of range
472: * (<tt>index < 0 || index > size()</tt>).
473: * @see List#listIterator(int)
474: */
475: public ListIterator listIterator(int index) {
476: return new ListItr(index);
477: }
478:
479: private class ListItr implements ListIterator {
480: private Entry lastReturned = header;
481: private Entry next;
482: private int nextIndex;
483: private int expectedModCount = modCount;
484:
485: ListItr(int index) {
486: if (index < 0 || index > size)
487: throw new IndexOutOfBoundsException("Index: " + index
488: + ", Size: " + size);
489: if (index < (size >> 1)) {
490: next = header.next;
491: for (nextIndex = 0; nextIndex < index; nextIndex++)
492: next = next.next;
493: } else {
494: next = header;
495: for (nextIndex = size; nextIndex > index; nextIndex--)
496: next = next.previous;
497: }
498: }
499:
500: public boolean hasNext() {
501: return nextIndex != size;
502: }
503:
504: public Object next() {
505: checkForComodification();
506: if (nextIndex == size)
507: throw new NoSuchElementException();
508:
509: lastReturned = next;
510: next = next.next;
511: nextIndex++;
512: return lastReturned.element;
513: }
514:
515: public boolean hasPrevious() {
516: return nextIndex != 0;
517: }
518:
519: public Object previous() {
520: if (nextIndex == 0)
521: throw new NoSuchElementException();
522:
523: lastReturned = next = next.previous;
524: nextIndex--;
525: checkForComodification();
526: return lastReturned.element;
527: }
528:
529: public int nextIndex() {
530: return nextIndex;
531: }
532:
533: public int previousIndex() {
534: return nextIndex - 1;
535: }
536:
537: public void remove() {
538: checkForComodification();
539: try {
540: LinkedList.this .remove(lastReturned);
541: } catch (NoSuchElementException e) {
542: throw new IllegalStateException();
543: }
544: if (next == lastReturned)
545: next = lastReturned.next;
546: else
547: nextIndex--;
548: lastReturned = header;
549: expectedModCount++;
550: }
551:
552: public void set(Object o) {
553: if (lastReturned == header)
554: throw new IllegalStateException();
555: checkForComodification();
556: lastReturned.element = o;
557: }
558:
559: public void add(Object o) {
560: checkForComodification();
561: lastReturned = header;
562: addBefore(o, next);
563: nextIndex++;
564: expectedModCount++;
565: }
566:
567: final void checkForComodification() {
568: if (modCount != expectedModCount)
569: throw new ConcurrentModificationException();
570: }
571: }
572:
573: private static class Entry {
574: Object element;
575: Entry next;
576: Entry previous;
577:
578: Entry(Object element, Entry next, Entry previous) {
579: this .element = element;
580: this .next = next;
581: this .previous = previous;
582: }
583: }
584:
585: private Entry addBefore(Object o, Entry e) {
586: Entry newEntry = new Entry(o, e, e.previous);
587: newEntry.previous.next = newEntry;
588: newEntry.next.previous = newEntry;
589: size++;
590: modCount++;
591: return newEntry;
592: }
593:
594: private void remove(Entry e) {
595: if (e == header)
596: throw new NoSuchElementException();
597:
598: e.previous.next = e.next;
599: e.next.previous = e.previous;
600: size--;
601: modCount++;
602: }
603:
604: /**
605: * Returns a shallow copy of this <tt>LinkedList</tt>. (The elements
606: * themselves are not cloned.)
607: *
608: * @return a shallow copy of this <tt>LinkedList</tt> instance.
609: */
610: public Object clone() {
611: LinkedList clone = null;
612: try {
613: clone = (LinkedList) super .clone();
614: } catch (CloneNotSupportedException e) {
615: throw new InternalError();
616: }
617:
618: // Put clone into "virgin" state
619: clone.header = new Entry(null, null, null);
620: clone.header.next = clone.header.previous = clone.header;
621: clone.size = 0;
622: clone.modCount = 0;
623:
624: // Initialize clone with our elements
625: for (Entry e = header.next; e != header; e = e.next)
626: clone.add(e.element);
627:
628: return clone;
629: }
630:
631: /**
632: * Returns an array containing all of the elements in this list
633: * in the correct order.
634: *
635: * @return an array containing all of the elements in this list
636: * in the correct order.
637: */
638: public Object[] toArray() {
639: Object[] result = new Object[size];
640: int i = 0;
641: for (Entry e = header.next; e != header; e = e.next)
642: result[i++] = e.element;
643: return result;
644: }
645:
646: /**
647: * Returns an array containing all of the elements in this list in
648: * the correct order; the runtime type of the returned array is that of
649: * the specified array. If the list fits in the specified array, it
650: * is returned therein. Otherwise, a new array is allocated with the
651: * runtime type of the specified array and the size of this list.<p>
652: *
653: * If the list fits in the specified array with room to spare
654: * (i.e., the array has more elements than the list),
655: * the element in the array immediately following the end of the
656: * collection is set to null. This is useful in determining the length
657: * of the list <i>only</i> if the caller knows that the list
658: * does not contain any null elements.
659: *
660: * @param a the array into which the elements of the list are to
661: * be stored, if it is big enough; otherwise, a new array of the
662: * same runtime type is allocated for this purpose.
663: * @return an array containing the elements of the list.
664: * @throws ArrayStoreException if the runtime type of a is not a
665: * supertype of the runtime type of every element in this list.
666: * @throws NullPointerException if the specified array is null.
667: */
668: public Object[] toArray(Object a[]) {
669: if (a.length < size)
670: a = (Object[]) java.lang.reflect.Array.newInstance(a
671: .getClass().getComponentType(), size);
672: int i = 0;
673: for (Entry e = header.next; e != header; e = e.next)
674: a[i++] = e.element;
675:
676: if (a.length > size)
677: a[size] = null;
678:
679: return a;
680: }
681:
682: private static final long serialVersionUID = 876323262645176354L;
683:
684: /**
685: * Save the state of this <tt>LinkedList</tt> instance to a stream (that
686: * is, serialize it).
687: *
688: * @serialData The size of the list (the number of elements it
689: * contains) is emitted (int), followed by all of its
690: * elements (each an Object) in the proper order.
691: */
692: private void writeObject(java.io.ObjectOutputStream s)
693: throws java.io.IOException {
694: // Write out any hidden serialization magic
695: s.defaultWriteObject();
696:
697: // Write out size
698: s.writeInt(size);
699:
700: // Write out all elements in the proper order.
701: for (Entry e = header.next; e != header; e = e.next)
702: s.writeObject(e.element);
703: }
704:
705: /**
706: * Reconstitute this <tt>LinkedList</tt> instance from a stream (that is
707: * deserialize it).
708: */
709: private void readObject(java.io.ObjectInputStream s)
710: throws java.io.IOException, ClassNotFoundException {
711: // Read in any hidden serialization magic
712: s.defaultReadObject();
713:
714: // Read in size
715: int size = s.readInt();
716:
717: // Initialize header
718: header = new Entry(null, null, null);
719: header.next = header.previous = header;
720:
721: // Read in all elements in the proper order.
722: for (int i = 0; i < size; i++)
723: add(s.readObject());
724: }
725: }
|