jaroslav@597: /* jaroslav@597: * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. jaroslav@597: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@597: * jaroslav@597: * This code is free software; you can redistribute it and/or modify it jaroslav@597: * under the terms of the GNU General Public License version 2 only, as jaroslav@597: * published by the Free Software Foundation. Oracle designates this jaroslav@597: * particular file as subject to the "Classpath" exception as provided jaroslav@597: * by Oracle in the LICENSE file that accompanied this code. jaroslav@597: * jaroslav@597: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@597: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@597: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@597: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@597: * accompanied this code). jaroslav@597: * jaroslav@597: * You should have received a copy of the GNU General Public License version jaroslav@597: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@597: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@597: * jaroslav@597: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@597: * or visit www.oracle.com if you need additional information or have any jaroslav@597: * questions. jaroslav@597: */ jaroslav@597: jaroslav@597: package java.util; jaroslav@597: jaroslav@597: /** jaroslav@597: * Doubly-linked list implementation of the {@code List} and {@code Deque} jaroslav@597: * interfaces. Implements all optional list operations, and permits all jaroslav@597: * elements (including {@code null}). jaroslav@597: * jaroslav@597: *

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

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

jaroslav@597:  *   List list = Collections.synchronizedList(new LinkedList(...));
jaroslav@597: * jaroslav@597: *

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

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

This class is a member of the jaroslav@597: * jaroslav@597: * Java Collections Framework. jaroslav@597: * jaroslav@597: * @author Josh Bloch jaroslav@597: * @see List jaroslav@597: * @see ArrayList jaroslav@597: * @since 1.2 jaroslav@597: * @param the type of elements held in this collection jaroslav@597: */ jaroslav@597: jaroslav@597: public class LinkedList jaroslav@597: extends AbstractSequentialList jaroslav@597: implements List, Deque, Cloneable, java.io.Serializable jaroslav@597: { jaroslav@597: transient int size = 0; jaroslav@597: jaroslav@597: /** jaroslav@597: * Pointer to first node. jaroslav@597: * Invariant: (first == null && last == null) || jaroslav@597: * (first.prev == null && first.item != null) jaroslav@597: */ jaroslav@597: transient Node first; jaroslav@597: jaroslav@597: /** jaroslav@597: * Pointer to last node. jaroslav@597: * Invariant: (first == null && last == null) || jaroslav@597: * (last.next == null && last.item != null) jaroslav@597: */ jaroslav@597: transient Node last; jaroslav@597: jaroslav@597: /** jaroslav@597: * Constructs an empty list. jaroslav@597: */ jaroslav@597: public LinkedList() { jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Constructs a list containing the elements of the specified jaroslav@597: * collection, in the order they are returned by the collection's jaroslav@597: * iterator. jaroslav@597: * jaroslav@597: * @param c the collection whose elements are to be placed into this list jaroslav@597: * @throws NullPointerException if the specified collection is null jaroslav@597: */ jaroslav@597: public LinkedList(Collection c) { jaroslav@597: this(); jaroslav@597: addAll(c); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Links e as first element. jaroslav@597: */ jaroslav@597: private void linkFirst(E e) { jaroslav@597: final Node f = first; jaroslav@597: final Node newNode = new Node<>(null, e, f); jaroslav@597: first = newNode; jaroslav@597: if (f == null) jaroslav@597: last = newNode; jaroslav@597: else jaroslav@597: f.prev = newNode; jaroslav@597: size++; jaroslav@597: modCount++; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Links e as last element. jaroslav@597: */ jaroslav@597: void linkLast(E e) { jaroslav@597: final Node l = last; jaroslav@597: final Node newNode = new Node<>(l, e, null); jaroslav@597: last = newNode; jaroslav@597: if (l == null) jaroslav@597: first = newNode; jaroslav@597: else jaroslav@597: l.next = newNode; jaroslav@597: size++; jaroslav@597: modCount++; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Inserts element e before non-null Node succ. jaroslav@597: */ jaroslav@597: void linkBefore(E e, Node succ) { jaroslav@597: // assert succ != null; jaroslav@597: final Node pred = succ.prev; jaroslav@597: final Node newNode = new Node<>(pred, e, succ); jaroslav@597: succ.prev = newNode; jaroslav@597: if (pred == null) jaroslav@597: first = newNode; jaroslav@597: else jaroslav@597: pred.next = newNode; jaroslav@597: size++; jaroslav@597: modCount++; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Unlinks non-null first node f. jaroslav@597: */ jaroslav@597: private E unlinkFirst(Node f) { jaroslav@597: // assert f == first && f != null; jaroslav@597: final E element = f.item; jaroslav@597: final Node next = f.next; jaroslav@597: f.item = null; jaroslav@597: f.next = null; // help GC jaroslav@597: first = next; jaroslav@597: if (next == null) jaroslav@597: last = null; jaroslav@597: else jaroslav@597: next.prev = null; jaroslav@597: size--; jaroslav@597: modCount++; jaroslav@597: return element; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Unlinks non-null last node l. jaroslav@597: */ jaroslav@597: private E unlinkLast(Node l) { jaroslav@597: // assert l == last && l != null; jaroslav@597: final E element = l.item; jaroslav@597: final Node prev = l.prev; jaroslav@597: l.item = null; jaroslav@597: l.prev = null; // help GC jaroslav@597: last = prev; jaroslav@597: if (prev == null) jaroslav@597: first = null; jaroslav@597: else jaroslav@597: prev.next = null; jaroslav@597: size--; jaroslav@597: modCount++; jaroslav@597: return element; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Unlinks non-null node x. jaroslav@597: */ jaroslav@597: E unlink(Node x) { jaroslav@597: // assert x != null; jaroslav@597: final E element = x.item; jaroslav@597: final Node next = x.next; jaroslav@597: final Node prev = x.prev; jaroslav@597: jaroslav@597: if (prev == null) { jaroslav@597: first = next; jaroslav@597: } else { jaroslav@597: prev.next = next; jaroslav@597: x.prev = null; jaroslav@597: } jaroslav@597: jaroslav@597: if (next == null) { jaroslav@597: last = prev; jaroslav@597: } else { jaroslav@597: next.prev = prev; jaroslav@597: x.next = null; jaroslav@597: } jaroslav@597: jaroslav@597: x.item = null; jaroslav@597: size--; jaroslav@597: modCount++; jaroslav@597: return element; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Returns the first element in this list. jaroslav@597: * jaroslav@597: * @return the first element in this list jaroslav@597: * @throws NoSuchElementException if this list is empty jaroslav@597: */ jaroslav@597: public E getFirst() { jaroslav@597: final Node f = first; jaroslav@597: if (f == null) jaroslav@597: throw new NoSuchElementException(); jaroslav@597: return f.item; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Returns the last element in this list. jaroslav@597: * jaroslav@597: * @return the last element in this list jaroslav@597: * @throws NoSuchElementException if this list is empty jaroslav@597: */ jaroslav@597: public E getLast() { jaroslav@597: final Node l = last; jaroslav@597: if (l == null) jaroslav@597: throw new NoSuchElementException(); jaroslav@597: return l.item; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Removes and returns the first element from this list. jaroslav@597: * jaroslav@597: * @return the first element from this list jaroslav@597: * @throws NoSuchElementException if this list is empty jaroslav@597: */ jaroslav@597: public E removeFirst() { jaroslav@597: final Node f = first; jaroslav@597: if (f == null) jaroslav@597: throw new NoSuchElementException(); jaroslav@597: return unlinkFirst(f); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Removes and returns the last element from this list. jaroslav@597: * jaroslav@597: * @return the last element from this list jaroslav@597: * @throws NoSuchElementException if this list is empty jaroslav@597: */ jaroslav@597: public E removeLast() { jaroslav@597: final Node l = last; jaroslav@597: if (l == null) jaroslav@597: throw new NoSuchElementException(); jaroslav@597: return unlinkLast(l); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Inserts the specified element at the beginning of this list. jaroslav@597: * jaroslav@597: * @param e the element to add jaroslav@597: */ jaroslav@597: public void addFirst(E e) { jaroslav@597: linkFirst(e); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Appends the specified element to the end of this list. jaroslav@597: * jaroslav@597: *

This method is equivalent to {@link #add}. jaroslav@597: * jaroslav@597: * @param e the element to add jaroslav@597: */ jaroslav@597: public void addLast(E e) { jaroslav@597: linkLast(e); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Returns {@code true} if this list contains the specified element. jaroslav@597: * More formally, returns {@code true} if and only if this list contains jaroslav@597: * at least one element {@code e} such that jaroslav@597: * (o==null ? e==null : o.equals(e)). jaroslav@597: * jaroslav@597: * @param o element whose presence in this list is to be tested jaroslav@597: * @return {@code true} if this list contains the specified element jaroslav@597: */ jaroslav@597: public boolean contains(Object o) { jaroslav@597: return indexOf(o) != -1; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Returns the number of elements in this list. jaroslav@597: * jaroslav@597: * @return the number of elements in this list jaroslav@597: */ jaroslav@597: public int size() { jaroslav@597: return size; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Appends the specified element to the end of this list. jaroslav@597: * jaroslav@597: *

This method is equivalent to {@link #addLast}. jaroslav@597: * jaroslav@597: * @param e element to be appended to this list jaroslav@597: * @return {@code true} (as specified by {@link Collection#add}) jaroslav@597: */ jaroslav@597: public boolean add(E e) { jaroslav@597: linkLast(e); jaroslav@597: return true; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Removes the first occurrence of the specified element from this list, jaroslav@597: * if it is present. If this list does not contain the element, it is jaroslav@597: * unchanged. More formally, removes the element with the lowest index jaroslav@597: * {@code i} such that jaroslav@597: * (o==null ? get(i)==null : o.equals(get(i))) jaroslav@597: * (if such an element exists). Returns {@code true} if this list jaroslav@597: * contained the specified element (or equivalently, if this list jaroslav@597: * changed as a result of the call). jaroslav@597: * jaroslav@597: * @param o element to be removed from this list, if present jaroslav@597: * @return {@code true} if this list contained the specified element jaroslav@597: */ jaroslav@597: public boolean remove(Object o) { jaroslav@597: if (o == null) { jaroslav@597: for (Node x = first; x != null; x = x.next) { jaroslav@597: if (x.item == null) { jaroslav@597: unlink(x); jaroslav@597: return true; jaroslav@597: } jaroslav@597: } jaroslav@597: } else { jaroslav@597: for (Node x = first; x != null; x = x.next) { jaroslav@597: if (o.equals(x.item)) { jaroslav@597: unlink(x); jaroslav@597: return true; jaroslav@597: } jaroslav@597: } jaroslav@597: } jaroslav@597: return false; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Appends all of the elements in the specified collection to the end of jaroslav@597: * this list, in the order that they are returned by the specified jaroslav@597: * collection's iterator. The behavior of this operation is undefined if jaroslav@597: * the specified collection is modified while the operation is in jaroslav@597: * progress. (Note that this will occur if the specified collection is jaroslav@597: * this list, and it's nonempty.) jaroslav@597: * jaroslav@597: * @param c collection containing elements to be added to this list jaroslav@597: * @return {@code true} if this list changed as a result of the call jaroslav@597: * @throws NullPointerException if the specified collection is null jaroslav@597: */ jaroslav@597: public boolean addAll(Collection c) { jaroslav@597: return addAll(size, c); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Inserts all of the elements in the specified collection into this jaroslav@597: * list, starting at the specified position. Shifts the element jaroslav@597: * currently at that position (if any) and any subsequent elements to jaroslav@597: * the right (increases their indices). The new elements will appear jaroslav@597: * in the list in the order that they are returned by the jaroslav@597: * specified collection's iterator. jaroslav@597: * jaroslav@597: * @param index index at which to insert the first element jaroslav@597: * from the specified collection jaroslav@597: * @param c collection containing elements to be added to this list jaroslav@597: * @return {@code true} if this list changed as a result of the call jaroslav@597: * @throws IndexOutOfBoundsException {@inheritDoc} jaroslav@597: * @throws NullPointerException if the specified collection is null jaroslav@597: */ jaroslav@597: public boolean addAll(int index, Collection c) { jaroslav@597: checkPositionIndex(index); jaroslav@597: jaroslav@597: Object[] a = c.toArray(); jaroslav@597: int numNew = a.length; jaroslav@597: if (numNew == 0) jaroslav@597: return false; jaroslav@597: jaroslav@597: Node pred, succ; jaroslav@597: if (index == size) { jaroslav@597: succ = null; jaroslav@597: pred = last; jaroslav@597: } else { jaroslav@597: succ = node(index); jaroslav@597: pred = succ.prev; jaroslav@597: } jaroslav@597: jaroslav@597: for (Object o : a) { jaroslav@597: @SuppressWarnings("unchecked") E e = (E) o; jaroslav@597: Node newNode = new Node<>(pred, e, null); jaroslav@597: if (pred == null) jaroslav@597: first = newNode; jaroslav@597: else jaroslav@597: pred.next = newNode; jaroslav@597: pred = newNode; jaroslav@597: } jaroslav@597: jaroslav@597: if (succ == null) { jaroslav@597: last = pred; jaroslav@597: } else { jaroslav@597: pred.next = succ; jaroslav@597: succ.prev = pred; jaroslav@597: } jaroslav@597: jaroslav@597: size += numNew; jaroslav@597: modCount++; jaroslav@597: return true; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Removes all of the elements from this list. jaroslav@597: * The list will be empty after this call returns. jaroslav@597: */ jaroslav@597: public void clear() { jaroslav@597: // Clearing all of the links between nodes is "unnecessary", but: jaroslav@597: // - helps a generational GC if the discarded nodes inhabit jaroslav@597: // more than one generation jaroslav@597: // - is sure to free memory even if there is a reachable Iterator jaroslav@597: for (Node x = first; x != null; ) { jaroslav@597: Node next = x.next; jaroslav@597: x.item = null; jaroslav@597: x.next = null; jaroslav@597: x.prev = null; jaroslav@597: x = next; jaroslav@597: } jaroslav@597: first = last = null; jaroslav@597: size = 0; jaroslav@597: modCount++; jaroslav@597: } jaroslav@597: jaroslav@597: jaroslav@597: // Positional Access Operations jaroslav@597: jaroslav@597: /** jaroslav@597: * Returns the element at the specified position in this list. jaroslav@597: * jaroslav@597: * @param index index of the element to return jaroslav@597: * @return the element at the specified position in this list jaroslav@597: * @throws IndexOutOfBoundsException {@inheritDoc} jaroslav@597: */ jaroslav@597: public E get(int index) { jaroslav@597: checkElementIndex(index); jaroslav@597: return node(index).item; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Replaces the element at the specified position in this list with the jaroslav@597: * specified element. jaroslav@597: * jaroslav@597: * @param index index of the element to replace jaroslav@597: * @param element element to be stored at the specified position jaroslav@597: * @return the element previously at the specified position jaroslav@597: * @throws IndexOutOfBoundsException {@inheritDoc} jaroslav@597: */ jaroslav@597: public E set(int index, E element) { jaroslav@597: checkElementIndex(index); jaroslav@597: Node x = node(index); jaroslav@597: E oldVal = x.item; jaroslav@597: x.item = element; jaroslav@597: return oldVal; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Inserts the specified element at the specified position in this list. jaroslav@597: * Shifts the element currently at that position (if any) and any jaroslav@597: * subsequent elements to the right (adds one to their indices). jaroslav@597: * jaroslav@597: * @param index index at which the specified element is to be inserted jaroslav@597: * @param element element to be inserted jaroslav@597: * @throws IndexOutOfBoundsException {@inheritDoc} jaroslav@597: */ jaroslav@597: public void add(int index, E element) { jaroslav@597: checkPositionIndex(index); jaroslav@597: jaroslav@597: if (index == size) jaroslav@597: linkLast(element); jaroslav@597: else jaroslav@597: linkBefore(element, node(index)); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Removes the element at the specified position in this list. Shifts any jaroslav@597: * subsequent elements to the left (subtracts one from their indices). jaroslav@597: * Returns the element that was removed from the list. jaroslav@597: * jaroslav@597: * @param index the index of the element to be removed jaroslav@597: * @return the element previously at the specified position jaroslav@597: * @throws IndexOutOfBoundsException {@inheritDoc} jaroslav@597: */ jaroslav@597: public E remove(int index) { jaroslav@597: checkElementIndex(index); jaroslav@597: return unlink(node(index)); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Tells if the argument is the index of an existing element. jaroslav@597: */ jaroslav@597: private boolean isElementIndex(int index) { jaroslav@597: return index >= 0 && index < size; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Tells if the argument is the index of a valid position for an jaroslav@597: * iterator or an add operation. jaroslav@597: */ jaroslav@597: private boolean isPositionIndex(int index) { jaroslav@597: return index >= 0 && index <= size; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Constructs an IndexOutOfBoundsException detail message. jaroslav@597: * Of the many possible refactorings of the error handling code, jaroslav@597: * this "outlining" performs best with both server and client VMs. jaroslav@597: */ jaroslav@597: private String outOfBoundsMsg(int index) { jaroslav@597: return "Index: "+index+", Size: "+size; jaroslav@597: } jaroslav@597: jaroslav@597: private void checkElementIndex(int index) { jaroslav@597: if (!isElementIndex(index)) jaroslav@597: throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); jaroslav@597: } jaroslav@597: jaroslav@597: private void checkPositionIndex(int index) { jaroslav@597: if (!isPositionIndex(index)) jaroslav@597: throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Returns the (non-null) Node at the specified element index. jaroslav@597: */ jaroslav@597: Node node(int index) { jaroslav@597: // assert isElementIndex(index); jaroslav@597: jaroslav@597: if (index < (size >> 1)) { jaroslav@597: Node x = first; jaroslav@597: for (int i = 0; i < index; i++) jaroslav@597: x = x.next; jaroslav@597: return x; jaroslav@597: } else { jaroslav@597: Node x = last; jaroslav@597: for (int i = size - 1; i > index; i--) jaroslav@597: x = x.prev; jaroslav@597: return x; jaroslav@597: } jaroslav@597: } jaroslav@597: jaroslav@597: // Search Operations jaroslav@597: jaroslav@597: /** jaroslav@597: * Returns the index of the first occurrence of the specified element jaroslav@597: * in this list, or -1 if this list does not contain the element. jaroslav@597: * More formally, returns the lowest index {@code i} such that jaroslav@597: * (o==null ? get(i)==null : o.equals(get(i))), jaroslav@597: * or -1 if there is no such index. jaroslav@597: * jaroslav@597: * @param o element to search for jaroslav@597: * @return the index of the first occurrence of the specified element in jaroslav@597: * this list, or -1 if this list does not contain the element jaroslav@597: */ jaroslav@597: public int indexOf(Object o) { jaroslav@597: int index = 0; jaroslav@597: if (o == null) { jaroslav@597: for (Node x = first; x != null; x = x.next) { jaroslav@597: if (x.item == null) jaroslav@597: return index; jaroslav@597: index++; jaroslav@597: } jaroslav@597: } else { jaroslav@597: for (Node x = first; x != null; x = x.next) { jaroslav@597: if (o.equals(x.item)) jaroslav@597: return index; jaroslav@597: index++; jaroslav@597: } jaroslav@597: } jaroslav@597: return -1; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Returns the index of the last occurrence of the specified element jaroslav@597: * in this list, or -1 if this list does not contain the element. jaroslav@597: * More formally, returns the highest index {@code i} such that jaroslav@597: * (o==null ? get(i)==null : o.equals(get(i))), jaroslav@597: * or -1 if there is no such index. jaroslav@597: * jaroslav@597: * @param o element to search for jaroslav@597: * @return the index of the last occurrence of the specified element in jaroslav@597: * this list, or -1 if this list does not contain the element jaroslav@597: */ jaroslav@597: public int lastIndexOf(Object o) { jaroslav@597: int index = size; jaroslav@597: if (o == null) { jaroslav@597: for (Node x = last; x != null; x = x.prev) { jaroslav@597: index--; jaroslav@597: if (x.item == null) jaroslav@597: return index; jaroslav@597: } jaroslav@597: } else { jaroslav@597: for (Node x = last; x != null; x = x.prev) { jaroslav@597: index--; jaroslav@597: if (o.equals(x.item)) jaroslav@597: return index; jaroslav@597: } jaroslav@597: } jaroslav@597: return -1; jaroslav@597: } jaroslav@597: jaroslav@597: // Queue operations. jaroslav@597: jaroslav@597: /** jaroslav@597: * Retrieves, but does not remove, the head (first element) of this list. jaroslav@597: * jaroslav@597: * @return the head of this list, or {@code null} if this list is empty jaroslav@597: * @since 1.5 jaroslav@597: */ jaroslav@597: public E peek() { jaroslav@597: final Node f = first; jaroslav@597: return (f == null) ? null : f.item; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Retrieves, but does not remove, the head (first element) of this list. jaroslav@597: * jaroslav@597: * @return the head of this list jaroslav@597: * @throws NoSuchElementException if this list is empty jaroslav@597: * @since 1.5 jaroslav@597: */ jaroslav@597: public E element() { jaroslav@597: return getFirst(); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Retrieves and removes the head (first element) of this list. jaroslav@597: * jaroslav@597: * @return the head of this list, or {@code null} if this list is empty jaroslav@597: * @since 1.5 jaroslav@597: */ jaroslav@597: public E poll() { jaroslav@597: final Node f = first; jaroslav@597: return (f == null) ? null : unlinkFirst(f); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Retrieves and removes the head (first element) of this list. jaroslav@597: * jaroslav@597: * @return the head of this list jaroslav@597: * @throws NoSuchElementException if this list is empty jaroslav@597: * @since 1.5 jaroslav@597: */ jaroslav@597: public E remove() { jaroslav@597: return removeFirst(); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Adds the specified element as the tail (last element) of this list. jaroslav@597: * jaroslav@597: * @param e the element to add jaroslav@597: * @return {@code true} (as specified by {@link Queue#offer}) jaroslav@597: * @since 1.5 jaroslav@597: */ jaroslav@597: public boolean offer(E e) { jaroslav@597: return add(e); jaroslav@597: } jaroslav@597: jaroslav@597: // Deque operations jaroslav@597: /** jaroslav@597: * Inserts the specified element at the front of this list. jaroslav@597: * jaroslav@597: * @param e the element to insert jaroslav@597: * @return {@code true} (as specified by {@link Deque#offerFirst}) jaroslav@597: * @since 1.6 jaroslav@597: */ jaroslav@597: public boolean offerFirst(E e) { jaroslav@597: addFirst(e); jaroslav@597: return true; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Inserts the specified element at the end of this list. jaroslav@597: * jaroslav@597: * @param e the element to insert jaroslav@597: * @return {@code true} (as specified by {@link Deque#offerLast}) jaroslav@597: * @since 1.6 jaroslav@597: */ jaroslav@597: public boolean offerLast(E e) { jaroslav@597: addLast(e); jaroslav@597: return true; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Retrieves, but does not remove, the first element of this list, jaroslav@597: * or returns {@code null} if this list is empty. jaroslav@597: * jaroslav@597: * @return the first element of this list, or {@code null} jaroslav@597: * if this list is empty jaroslav@597: * @since 1.6 jaroslav@597: */ jaroslav@597: public E peekFirst() { jaroslav@597: final Node f = first; jaroslav@597: return (f == null) ? null : f.item; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Retrieves, but does not remove, the last element of this list, jaroslav@597: * or returns {@code null} if this list is empty. jaroslav@597: * jaroslav@597: * @return the last element of this list, or {@code null} jaroslav@597: * if this list is empty jaroslav@597: * @since 1.6 jaroslav@597: */ jaroslav@597: public E peekLast() { jaroslav@597: final Node l = last; jaroslav@597: return (l == null) ? null : l.item; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Retrieves and removes the first element of this list, jaroslav@597: * or returns {@code null} if this list is empty. jaroslav@597: * jaroslav@597: * @return the first element of this list, or {@code null} if jaroslav@597: * this list is empty jaroslav@597: * @since 1.6 jaroslav@597: */ jaroslav@597: public E pollFirst() { jaroslav@597: final Node f = first; jaroslav@597: return (f == null) ? null : unlinkFirst(f); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Retrieves and removes the last element of this list, jaroslav@597: * or returns {@code null} if this list is empty. jaroslav@597: * jaroslav@597: * @return the last element of this list, or {@code null} if jaroslav@597: * this list is empty jaroslav@597: * @since 1.6 jaroslav@597: */ jaroslav@597: public E pollLast() { jaroslav@597: final Node l = last; jaroslav@597: return (l == null) ? null : unlinkLast(l); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Pushes an element onto the stack represented by this list. In other jaroslav@597: * words, inserts the element at the front of this list. jaroslav@597: * jaroslav@597: *

This method is equivalent to {@link #addFirst}. jaroslav@597: * jaroslav@597: * @param e the element to push jaroslav@597: * @since 1.6 jaroslav@597: */ jaroslav@597: public void push(E e) { jaroslav@597: addFirst(e); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Pops an element from the stack represented by this list. In other jaroslav@597: * words, removes and returns the first element of this list. jaroslav@597: * jaroslav@597: *

This method is equivalent to {@link #removeFirst()}. jaroslav@597: * jaroslav@597: * @return the element at the front of this list (which is the top jaroslav@597: * of the stack represented by this list) jaroslav@597: * @throws NoSuchElementException if this list is empty jaroslav@597: * @since 1.6 jaroslav@597: */ jaroslav@597: public E pop() { jaroslav@597: return removeFirst(); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Removes the first occurrence of the specified element in this jaroslav@597: * list (when traversing the list from head to tail). If the list jaroslav@597: * does not contain the element, it is unchanged. jaroslav@597: * jaroslav@597: * @param o element to be removed from this list, if present jaroslav@597: * @return {@code true} if the list contained the specified element jaroslav@597: * @since 1.6 jaroslav@597: */ jaroslav@597: public boolean removeFirstOccurrence(Object o) { jaroslav@597: return remove(o); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Removes the last occurrence of the specified element in this jaroslav@597: * list (when traversing the list from head to tail). If the list jaroslav@597: * does not contain the element, it is unchanged. jaroslav@597: * jaroslav@597: * @param o element to be removed from this list, if present jaroslav@597: * @return {@code true} if the list contained the specified element jaroslav@597: * @since 1.6 jaroslav@597: */ jaroslav@597: public boolean removeLastOccurrence(Object o) { jaroslav@597: if (o == null) { jaroslav@597: for (Node x = last; x != null; x = x.prev) { jaroslav@597: if (x.item == null) { jaroslav@597: unlink(x); jaroslav@597: return true; jaroslav@597: } jaroslav@597: } jaroslav@597: } else { jaroslav@597: for (Node x = last; x != null; x = x.prev) { jaroslav@597: if (o.equals(x.item)) { jaroslav@597: unlink(x); jaroslav@597: return true; jaroslav@597: } jaroslav@597: } jaroslav@597: } jaroslav@597: return false; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Returns a list-iterator of the elements in this list (in proper jaroslav@597: * sequence), starting at the specified position in the list. jaroslav@597: * Obeys the general contract of {@code List.listIterator(int)}.

jaroslav@597: * jaroslav@597: * The list-iterator is fail-fast: if the list is structurally jaroslav@597: * modified at any time after the Iterator is created, in any way except jaroslav@597: * through the list-iterator's own {@code remove} or {@code add} jaroslav@597: * methods, the list-iterator will throw a jaroslav@597: * {@code ConcurrentModificationException}. Thus, in the face of jaroslav@597: * concurrent modification, the iterator fails quickly and cleanly, rather jaroslav@597: * than risking arbitrary, non-deterministic behavior at an undetermined jaroslav@597: * time in the future. jaroslav@597: * jaroslav@597: * @param index index of the first element to be returned from the jaroslav@597: * list-iterator (by a call to {@code next}) jaroslav@597: * @return a ListIterator of the elements in this list (in proper jaroslav@597: * sequence), starting at the specified position in the list jaroslav@597: * @throws IndexOutOfBoundsException {@inheritDoc} jaroslav@597: * @see List#listIterator(int) jaroslav@597: */ jaroslav@597: public ListIterator listIterator(int index) { jaroslav@597: checkPositionIndex(index); jaroslav@597: return new ListItr(index); jaroslav@597: } jaroslav@597: jaroslav@597: private class ListItr implements ListIterator { jaroslav@597: private Node lastReturned = null; jaroslav@597: private Node next; jaroslav@597: private int nextIndex; jaroslav@597: private int expectedModCount = modCount; jaroslav@597: jaroslav@597: ListItr(int index) { jaroslav@597: // assert isPositionIndex(index); jaroslav@597: next = (index == size) ? null : node(index); jaroslav@597: nextIndex = index; jaroslav@597: } jaroslav@597: jaroslav@597: public boolean hasNext() { jaroslav@597: return nextIndex < size; jaroslav@597: } jaroslav@597: jaroslav@597: public E next() { jaroslav@597: checkForComodification(); jaroslav@597: if (!hasNext()) jaroslav@597: throw new NoSuchElementException(); jaroslav@597: jaroslav@597: lastReturned = next; jaroslav@597: next = next.next; jaroslav@597: nextIndex++; jaroslav@597: return lastReturned.item; jaroslav@597: } jaroslav@597: jaroslav@597: public boolean hasPrevious() { jaroslav@597: return nextIndex > 0; jaroslav@597: } jaroslav@597: jaroslav@597: public E previous() { jaroslav@597: checkForComodification(); jaroslav@597: if (!hasPrevious()) jaroslav@597: throw new NoSuchElementException(); jaroslav@597: jaroslav@597: lastReturned = next = (next == null) ? last : next.prev; jaroslav@597: nextIndex--; jaroslav@597: return lastReturned.item; jaroslav@597: } jaroslav@597: jaroslav@597: public int nextIndex() { jaroslav@597: return nextIndex; jaroslav@597: } jaroslav@597: jaroslav@597: public int previousIndex() { jaroslav@597: return nextIndex - 1; jaroslav@597: } jaroslav@597: jaroslav@597: public void remove() { jaroslav@597: checkForComodification(); jaroslav@597: if (lastReturned == null) jaroslav@597: throw new IllegalStateException(); jaroslav@597: jaroslav@597: Node lastNext = lastReturned.next; jaroslav@597: unlink(lastReturned); jaroslav@597: if (next == lastReturned) jaroslav@597: next = lastNext; jaroslav@597: else jaroslav@597: nextIndex--; jaroslav@597: lastReturned = null; jaroslav@597: expectedModCount++; jaroslav@597: } jaroslav@597: jaroslav@597: public void set(E e) { jaroslav@597: if (lastReturned == null) jaroslav@597: throw new IllegalStateException(); jaroslav@597: checkForComodification(); jaroslav@597: lastReturned.item = e; jaroslav@597: } jaroslav@597: jaroslav@597: public void add(E e) { jaroslav@597: checkForComodification(); jaroslav@597: lastReturned = null; jaroslav@597: if (next == null) jaroslav@597: linkLast(e); jaroslav@597: else jaroslav@597: linkBefore(e, next); jaroslav@597: nextIndex++; jaroslav@597: expectedModCount++; jaroslav@597: } jaroslav@597: jaroslav@597: final void checkForComodification() { jaroslav@597: if (modCount != expectedModCount) jaroslav@597: throw new ConcurrentModificationException(); jaroslav@597: } jaroslav@597: } jaroslav@597: jaroslav@597: private static class Node { jaroslav@597: E item; jaroslav@597: Node next; jaroslav@597: Node prev; jaroslav@597: jaroslav@597: Node(Node prev, E element, Node next) { jaroslav@597: this.item = element; jaroslav@597: this.next = next; jaroslav@597: this.prev = prev; jaroslav@597: } jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * @since 1.6 jaroslav@597: */ jaroslav@597: public Iterator descendingIterator() { jaroslav@597: return new DescendingIterator(); jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Adapter to provide descending iterators via ListItr.previous jaroslav@597: */ jaroslav@597: private class DescendingIterator implements Iterator { jaroslav@597: private final ListItr itr = new ListItr(size()); jaroslav@597: public boolean hasNext() { jaroslav@597: return itr.hasPrevious(); jaroslav@597: } jaroslav@597: public E next() { jaroslav@597: return itr.previous(); jaroslav@597: } jaroslav@597: public void remove() { jaroslav@597: itr.remove(); jaroslav@597: } jaroslav@597: } jaroslav@597: jaroslav@597: @SuppressWarnings("unchecked") jaroslav@597: private LinkedList superClone() { jaroslav@597: try { jaroslav@597: return (LinkedList) super.clone(); jaroslav@597: } catch (CloneNotSupportedException e) { jaroslav@597: throw new InternalError(); jaroslav@597: } jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Returns a shallow copy of this {@code LinkedList}. (The elements jaroslav@597: * themselves are not cloned.) jaroslav@597: * jaroslav@597: * @return a shallow copy of this {@code LinkedList} instance jaroslav@597: */ jaroslav@597: public Object clone() { jaroslav@597: LinkedList clone = superClone(); jaroslav@597: jaroslav@597: // Put clone into "virgin" state jaroslav@597: clone.first = clone.last = null; jaroslav@597: clone.size = 0; jaroslav@597: clone.modCount = 0; jaroslav@597: jaroslav@597: // Initialize clone with our elements jaroslav@597: for (Node x = first; x != null; x = x.next) jaroslav@597: clone.add(x.item); jaroslav@597: jaroslav@597: return clone; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Returns an array containing all of the elements in this list jaroslav@597: * in proper sequence (from first to last element). jaroslav@597: * jaroslav@597: *

The returned array will be "safe" in that no references to it are jaroslav@597: * maintained by this list. (In other words, this method must allocate jaroslav@597: * a new array). The caller is thus free to modify the returned array. jaroslav@597: * jaroslav@597: *

This method acts as bridge between array-based and collection-based jaroslav@597: * APIs. jaroslav@597: * jaroslav@597: * @return an array containing all of the elements in this list jaroslav@597: * in proper sequence jaroslav@597: */ jaroslav@597: public Object[] toArray() { jaroslav@597: Object[] result = new Object[size]; jaroslav@597: int i = 0; jaroslav@597: for (Node x = first; x != null; x = x.next) jaroslav@597: result[i++] = x.item; jaroslav@597: return result; jaroslav@597: } jaroslav@597: jaroslav@597: /** jaroslav@597: * Returns an array containing all of the elements in this list in jaroslav@597: * proper sequence (from first to last element); the runtime type of jaroslav@597: * the returned array is that of the specified array. If the list fits jaroslav@597: * in the specified array, it is returned therein. Otherwise, a new jaroslav@597: * array is allocated with the runtime type of the specified array and jaroslav@597: * the size of this list. jaroslav@597: * jaroslav@597: *

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

Like the {@link #toArray()} method, this method acts as bridge between jaroslav@597: * array-based and collection-based APIs. Further, this method allows jaroslav@597: * precise control over the runtime type of the output array, and may, jaroslav@597: * under certain circumstances, be used to save allocation costs. jaroslav@597: * jaroslav@597: *

Suppose {@code x} is a list known to contain only strings. jaroslav@597: * The following code can be used to dump the list into a newly jaroslav@597: * allocated array of {@code String}: jaroslav@597: * jaroslav@597: *

jaroslav@597:      *     String[] y = x.toArray(new String[0]);
jaroslav@597: * jaroslav@597: * Note that {@code toArray(new Object[0])} is identical in function to jaroslav@597: * {@code toArray()}. jaroslav@597: * jaroslav@597: * @param a the array into which the elements of the list are to jaroslav@597: * be stored, if it is big enough; otherwise, a new array of the jaroslav@597: * same runtime type is allocated for this purpose. jaroslav@597: * @return an array containing the elements of the list jaroslav@597: * @throws ArrayStoreException if the runtime type of the specified array jaroslav@597: * is not a supertype of the runtime type of every element in jaroslav@597: * this list jaroslav@597: * @throws NullPointerException if the specified array is null jaroslav@597: */ jaroslav@597: @SuppressWarnings("unchecked") jaroslav@597: public T[] toArray(T[] a) { jaroslav@597: if (a.length < size) jaroslav@597: a = (T[])java.lang.reflect.Array.newInstance( jaroslav@597: a.getClass().getComponentType(), size); jaroslav@597: int i = 0; jaroslav@597: Object[] result = a; jaroslav@597: for (Node x = first; x != null; x = x.next) jaroslav@597: result[i++] = x.item; jaroslav@597: jaroslav@597: if (a.length > size) jaroslav@597: a[size] = null; jaroslav@597: jaroslav@597: return a; jaroslav@597: } jaroslav@597: jaroslav@597: private static final long serialVersionUID = 876323262645176354L; jaroslav@597: jaroslav@597: }