Linked list implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface, the LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue (deque).

The class implements the Queue interface, providing first-in-first-out queue operations for add, poll, etc. Other stack and deque operations could be easily recast in terms of the standard list operations. They're included here primarily for convenience, though they may run slightly faster than the equivalent List operations.

All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.

Note that this implementation is not synchronized. If multiple threads access a list concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

     List list = Collections.synchronizedList(new LinkedList(...));
 

The iterators returned by the this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the Iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

@author
Josh Bloch
@version
1.61, 02/19/04
@since
1.2
@param
the type of elements held in this collection
Constructs an empty list.
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
Parameters
cthe collection whose elements are to be placed into this list.
Throws
NullPointerExceptionif the specified collection is null.
Appends the specified element to the end of this list.
Parameters
oelement to be appended to this list.
Return
true (as per the general contract of Collection.add).
Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
Parameters
indexindex at which the specified element is to be inserted.
elementelement to be inserted.
Throws
IndexOutOfBoundsExceptionif the specified index is out of range (index < 0 || index > size()).
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified Collection is this list, and this list is nonempty.)
Parameters
cthe elements to be inserted into this list.
Return
true if this list changed as a result of the call.
Throws
NullPointerExceptionif the specified collection is null.
Inserts all of the elements in the specified collection into this list, starting at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). The new elements will appear in the list in the order that they are returned by the specified collection's iterator.
Parameters
indexindex at which to insert first element from the specified collection.
celements to be inserted into this list.
Return
true if this list changed as a result of the call.
Throws
IndexOutOfBoundsExceptionif the specified index is out of range (index < 0 || index > size()).
NullPointerExceptionif the specified collection is null.
Inserts the given element at the beginning of this list.
Parameters
othe element to be inserted at the beginning of this list.
Appends the given element to the end of this list. (Identical in function to the add method; included only for consistency.)
Parameters
othe element to be inserted at the end of this list.
Removes all of the elements from this list.
Returns a shallow copy of this LinkedList. (The elements themselves are not cloned.)
Return
a shallow copy of this LinkedList instance.
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
Parameters
oelement whose presence in this list is to be tested.
Return
true if this list contains the specified element.
Returns true if this collection contains all of the elements in the specified collection.

This implementation iterates over the specified collection, checking each element returned by the iterator in turn to see if it's contained in this collection. If all elements are so contained true is returned, otherwise false.

Parameters
ccollection to be checked for containment in this collection.
Return
true if this collection contains all of the elements in the specified collection.
Throws
NullPointerExceptionif the specified collection is null.
Retrieves, but does not remove, the head of this queue. This method differs from the peek method only in that it throws an exception if this queue is empty.
Return
the head of this queue.
Throws
NoSuchElementExceptionif this queue is empty.
Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two lists are defined to be equal if they contain the same elements in the same order. This definition ensures that the equals method works properly across different implementations of the List interface.
Parameters
othe object to be compared for equality with this list.
Return
true if the specified object is equal to this list.
Returns the element at the specified position in this list.
Parameters
indexindex of element to return.
Return
the element at the specified position in this list.
Throws
IndexOutOfBoundsExceptionif the specified index is out of range (index < 0 || index >= size()).
Returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
Return
The java.lang.Class object that represents the runtime class of the object. The result is of type {@code Class} where X is the erasure of the static type of the expression on which getClass is called.
Returns the first element in this list.
Return
the first element in this list.
Throws
NoSuchElementExceptionif this list is empty.
Returns the last element in this list.
Return
the last element in this list.
Throws
NoSuchElementExceptionif this list is empty.
Returns the hash code value for this list. The hash code of a list is defined to be the result of the following calculation:
  hashCode = 1;
  Iterator i = list.iterator();
  while (i.hasNext()) {
      Object obj = i.next();
      hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
  }
 
This ensures that list1.equals(list2) implies that list1.hashCode()==list2.hashCode() for any two lists, list1 and list2, as required by the general contract of Object.hashCode.
Return
the hash code value for this list.
Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
Parameters
oelement to search for.
Return
the index in this list of the first occurrence of the specified element, or -1 if the list does not contain this element.
Returns true if this collection contains no elements.

This implementation returns size() == 0.

Return
true if this collection contains no elements.
Returns an iterator over the elements in this list (in proper sequence).

This implementation merely returns a list iterator over the list.

Return
an iterator over the elements in this list (in proper sequence).
Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element. More formally, returns the highest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.
Parameters
oelement to search for.
Return
the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
Returns an iterator of the elements in this list (in proper sequence). This implementation returns listIterator(0).
Return
an iterator of the elements in this list (in proper sequence).
Returns a list-iterator of the elements in this list (in proper sequence), starting at the specified position in the list. Obeys the general contract of List.listIterator(int).

The list-iterator is fail-fast: if the list is structurally modified at any time after the Iterator is created, in any way except through the list-iterator's own remove or add methods, the list-iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Parameters
indexindex of first element to be returned from the list-iterator (by a call to next).
Return
a ListIterator of the elements in this list (in proper sequence), starting at the specified position in the list.
Throws
IndexOutOfBoundsExceptionif index is out of range (index < 0 || index > size()).
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.

The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
Inserts the specified element into this queue, if possible. When using queues that may impose insertion restrictions (for example capacity bounds), method offer is generally preferable to method Collection#add , which can fail to insert an element only by throwing an exception.
Parameters
othe element to insert.
Return
true if it was possible to add the element to this queue, else false
Retrieves, but does not remove, the head of this queue, returning null if this queue is empty.
Return
the head of this queue, or null if this queue is empty.
Retrieves and removes the head of this queue, or null if this queue is empty.
Return
the head of this queue, or null if this queue is empty.
Retrieves and removes the head of this queue. This method differs from the poll method in that it throws an exception if this queue is empty.
Return
the head of this queue.
Throws
NoSuchElementExceptionif this queue is empty.
Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.
Parameters
indexthe index of the element to removed.
Return
the element previously at the specified position.
Throws
IndexOutOfBoundsExceptionif the specified index is out of range (index < 0 || index >= size()).
Removes the first occurrence of the specified element in this list. If the list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists).
Parameters
oelement to be removed from this list, if present.
Return
true if the list contained the specified element.
Removes from this collection all of its elements that are contained in the specified collection (optional operation).

This implementation iterates over this collection, checking each element returned by the iterator in turn to see if it's contained in the specified collection. If it's so contained, it's removed from this collection with the iterator's remove method.

Note that this implementation will throw an UnsupportedOperationException if the iterator returned by the iterator method does not implement the remove method and this collection contains one or more elements in common with the specified collection.

Parameters
celements to be removed from this collection.
Return
true if this collection changed as a result of the call.
Throws
UnsupportedOperationExceptionif the removeAll method is not supported by this collection.
NullPointerExceptionif the specified collection is null.
Removes and returns the first element from this list.
Return
the first element from this list.
Throws
NoSuchElementExceptionif this list is empty.
Removes and returns the last element from this list.
Return
the last element from this list.
Throws
NoSuchElementExceptionif this list is empty.
Retains only the elements in this collection that are contained in the specified collection (optional operation). In other words, removes from this collection all of its elements that are not contained in the specified collection.

This implementation iterates over this collection, checking each element returned by the iterator in turn to see if it's contained in the specified collection. If it's not so contained, it's removed from this collection with the iterator's remove method.

Note that this implementation will throw an UnsupportedOperationException if the iterator returned by the iterator method does not implement the remove method and this collection contains one or more elements not present in the specified collection.

Parameters
celements to be retained in this collection.
Return
true if this collection changed as a result of the call.
Throws
UnsupportedOperationExceptionif the retainAll method is not supported by this Collection.
NullPointerExceptionif the specified collection is null.
Replaces the element at the specified position in this list with the specified element.
Parameters
indexindex of element to replace.
elementelement to be stored at the specified position.
Return
the element previously at the specified position.
Throws
IndexOutOfBoundsExceptionif the specified index is out of range (index < 0 || index >= size()).
Returns the number of elements in this list.
Return
the number of elements in this list.
Returns a view of the portion of this list between fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by operating on a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:

     list.subList(from, to).clear();
 
Similar idioms may be constructed for indexOf and lastIndexOf, and all of the algorithms in the Collections class can be applied to a subList.

The semantics of the list returned by this method become undefined if the backing list (i.e., this list) is structurally modified in any way other than via the returned list. (Structural modifications are those that change the size of the list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)

This implementation returns a list that subclasses AbstractList. The subclass stores, in private fields, the offset of the subList within the backing list, the size of the subList (which can change over its lifetime), and the expected modCount value of the backing list. There are two variants of the subclass, one of which implements RandomAccess. If this list implements RandomAccess the returned list will be an instance of the subclass that implements RandomAccess.

The subclass's set(int, Object), get(int), add(int, Object), remove(int), addAll(int, Collection) and removeRange(int, int) methods all delegate to the corresponding methods on the backing abstract list, after bounds-checking the index and adjusting for the offset. The addAll(Collection c) method merely returns addAll(size, c).

The listIterator(int) method returns a "wrapper object" over a list iterator on the backing list, which is created with the corresponding method on the backing list. The iterator method merely returns listIterator(), and the size method merely returns the subclass's size field.

All methods first check to see if the actual modCount of the backing list is equal to its expected value, and throw a ConcurrentModificationException if it is not.

Parameters
fromIndexlow endpoint (inclusive) of the subList.
toIndexhigh endpoint (exclusive) of the subList.
Return
a view of the specified range within this list.
Throws
IndexOutOfBoundsExceptionendpoint index value out of range (fromIndex < 0 || toIndex > size)
IllegalArgumentExceptionendpoint indices out of order (fromIndex > toIndex)
Returns an array containing all of the elements in this list in the correct order.
Return
an array containing all of the elements in this list in the correct order.
Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following the end of the collection is set to null. This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements.

Parameters
athe array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
Return
an array containing the elements of the list.
Throws
ArrayStoreExceptionif the runtime type of a is not a supertype of the runtime type of every element in this list.
NullPointerExceptionif the specified array is null.
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).

This implementation creates an empty string buffer, appends a left square bracket, and iterates over the collection appending the string representation of each element in turn. After appending each element except the last, the string ", " is appended. Finally a right bracket is appended. A string is obtained from the string buffer, and returned.

Return
a string representation of this collection.
Causes current thread to wait until another thread invokes the method or the method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait();
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Throws
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until either another thread invokes the method or the method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor.

This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

  • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
  • Some other thread invokes the notifyAll method for this object.
  • Some other thread interrupts thread T.
  • The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.
The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object; once it has gained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. In other words, waits should always occur in loops, like this one:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout);
         ... // Perform action appropriate to condition
     }
 
(For more information on this topic, see Section 3.2.3 in Doug Lea's "Concurrent Programming in Java (Second Edition)" (Addison-Wesley, 2000), or Item 50 in Joshua Bloch's "Effective Java Programming Language Guide" (Addison-Wesley, 2001).

If the current thread is interrupted by another thread while it is waiting, then an InterruptedException is thrown. This exception is not thrown until the lock status of this object has been restored as described above.

Note that the wait method, as it places the current thread into the wait set for this object, unlocks only this object; any other objects on which the current thread may be synchronized remain locked while the thread waits.

This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Parameters
timeoutthe maximum time to wait in milliseconds.
Throws
IllegalArgumentExceptionif the value of timeout is negative.
IllegalMonitorStateExceptionif the current thread is not the owner of the object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
Causes current thread to wait until another thread invokes the method or the method for this object, or some other thread interrupts the current thread, or a certain amount of real time has elapsed.

This method is similar to the wait method of one argument, but it allows finer control over the amount of time to wait for a notification before giving up. The amount of real time, measured in nanoseconds, is given by:

 1000000*timeout+nanos

In all other respects, this method does the same thing as the method of one argument. In particular, wait(0, 0) means the same thing as wait(0).

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:

  • Another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.
  • The timeout period, specified by timeout milliseconds plus nanos nanoseconds arguments, has elapsed.

The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:

     synchronized (obj) {
         while (<condition does not hold>)
             obj.wait(timeout, nanos);
         ... // Perform action appropriate to condition
     }
 
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.
Parameters
timeoutthe maximum time to wait in milliseconds.
nanosadditional time, in nanoseconds range 0-999999.
Throws
IllegalArgumentExceptionif the value of timeout is negative or the value of nanos is not in the range 0-999999.
IllegalMonitorStateExceptionif the current thread is not the owner of this object's monitor.
InterruptedExceptionif another thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.