Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
What's the best way to make a linked list in Java?
(1) List<?> myList = new ArrayList<?>(); (2) ArrayList<?> myList = new ArrayList<?>(); I understand that with (1), implementations of the List interface can be swapped. It seems that (1) is typically used in an application regardless of need (myself I always use this). I am wondering if anyone uses (2)? Also, how often (and can I please get an example) does the sit...
I'm writing a Mandelbrot fractal viewer, and I would like to implement color cycling in a smart way. Given an image, I would like to modify its IndexColorModel. As far as I can tell, there's no way to modify an IndexColorModel, and there's no way to give an image a new IndexColorModel. In fact, I think there's no way to extract its color model or image data. It seems that the only solution is...
Hi I have found this code in the internet and it was for arrays ,I want to change it for doubly linked list(instead of index we should use pointer) would you please help me that how can i change merge method(I have changed sort method by myself) also this is not my home work ,I love working with linked list!! public class MergeSort { private DoublyLinkedList LocalDoublyLinkedList; public Mer...
I am having an issue with some process wrapping, and it's only occurring in Windows XP. This code works perfectly in Windows 7. I'm really stumped as to why the streams are empty in XP. I've also tried using the String[] version of Process.Exec() and it made no difference. I am using the following class to read from the process' STDOUT and STDERR (an instance for each stream): import java...
Is there any (well implemented) intrusive double linked list class(es) available for Java? Or should I do my own? Boost has it for C++: http://beta.boost.org/doc/libs/1_40_0/doc/html/boost/intrusive/list.html. Intrusive list is a container having (in this case) next and prev pointers within element, so typical list operations like replace and remove can be directly targeted into elementary cla...
What is the best way to do a resizable array in Java? I tried using Vector, but that shifts all elements over by when when you do an insert, and I need an array that can grow but the elements stay in place. I'm sure there's a simple answer for this, but I still not quite sure.
As far as I know, the concept of a linked list is a bunch of object connected to each other by having a 'next' and sometimes 'previous' attribute to traverse the objects. I noticed in Java, you can create a LinkedList object...but treat it like an array/list/sequence by using the same methods such as .add(), .get(), etc. So, is LinkedList internally an array-like sequence?
I am working on a piece of code with Iterator and getting a ConcurrentModificationException at the line a when I run the program from my IDE on windows-- LinkedList ll =new LinkedList(); . . . . . . Iterator iter = ll.iterator(); int i=0; while (iter.hasNext()) { // GrammarSection agrammarSection = (GrammarSection) iter.next(); //a String s1 = (String) iter.next()...
List<String> ll = new LinkedList<String>("String1","String2",...); I want something like above. Is the above line possible in java...?
Is it possible to add elements to a collection while iterating over it? More specifically, I would like to iterate over a collection, and if an element satisfies a certain condition I want to add some other elements to the collection, and make sure that these added elements are iterated over as well. (I realise that this could lead to an unterminating loop, but I'm pretty sure it won't in my ...
I have a private LinkedList in a Java class & will frequently need to retrieve the last element in the list. The lists need to scale, so I'm trying to decide whether I need to keep a reference to the last element when I make changes (to achieve O(1)) or if the LinkedList class does that already with the getLast() call. What is the big-O cost of LinkedList.getLast() and is it documented? (...
Say I have a java.util.List list and I want to create a new List by adding an element e to the beginning of list (i.e., I want to cons e and list). For example, if list is [1,2,3,4] and e is 5, then cons(e,list) will be [5,1,2,3,4] It's OK for the elements of list and cons(e,list) to be shared, but list should not be modified. What is the simplest and/or most efficient way to implement c...
I'm new to this site but it was recommended to me by a good friend. Let me start by saying I am a student and I am currently studying Java programming as part of my Bachelor's degree. I am here and posting because I am having a problem trying to understand the question asked in the assignment that has been given. Both my book (Big Java 4th edition) and my instructor are not very clear on what ...
Does anyone know if it's possible to merge two lists (or any collection) in constant time in Java ? http://www.cppreference.com/wiki/stl/list/splice It's so easy to do that using linked lists in C... Thanks,
I've something like this Object[] myObjects = ...(initialized in some way)... int[] elemToRemove = new int[]{3,4,6,8,...} What's the most efficient way of removing the elements of index position 3,4,6,8... from myObjects ? I'd like to implement an efficient Utility method with a signature like public Object[] removeElements(Object[] object, int[] elementsToRemove) {...} The Object[] that ...
I'm a beginner and I want to write Java code in eclipse. This program takes two LinkedLists of integers (for example, a and b) and makes a LinkedList (for example d) in which every element is the sum of elements from a and b. However, I can't add these two elements from a and b because they are Objects Example: a=[3,4,6,7,8] b=[4,3,7,5,3,2,1] ------ d=[7,7,13,12,11,2,1]
I want to be able to have LinkedList.contains() return true for a custom comparator. Suppose that I have 1 LinkedList and 2 objects LinkedList<MyObject> myList = new LinkedList<MyObject>(); MyObject a = new MyObject("HELLO"); MyObject b = new MyObject("HELLO"); Technicaly, both objects are identical in terms of comparison (MyObject implements Comparable) ( a == b ) == true h...
My gut tells me there is no good way to achieve this, but, unlike Mr. Stephen Colbert, I'd rather trust a community of developers than my gut... Is there a known way to efficiently implement a "best of both worlds" list, one that provides random access by index and O(1) insertion/removal like a linked list? I foresee two possible outcomes: either "No, this is impossible, for the following obv...
I only see a Queue interface, is there no Queue class in the Java Collections?
I need some help with my homework assignement. My assignment is to create a program that creates a Till object, takes a payment, issues exact change, tells me which coins I need to use and then tells me how much is in the till after. Below is the code I have written. The USmoney class is done and is working. The teacher offered a cheat sheet. However it's the main class (CoinCalc), getting the ...
  /*
   * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.util;

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.

The class implements the Deque interface, providing first-in-first-out queue operations for add, poll, along with other stack and deque 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 linked 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 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.

Parameters:
<E> the type of elements held in this collection
Author(s):
Josh Bloch
Since:
1.2
See also:
List
ArrayList
Vector
 
 
 public class LinkedList<E>
     extends AbstractSequentialList<E>
     implements List<E>, Deque<E>, Cloneablejava.io.Serializable
 {
     private transient Entry<E> header = new Entry<E>(nullnullnull);
     private transient int size = 0;

    
Constructs an empty list.
    public LinkedList() {
        . = . = ;
    }

    
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

Parameters:
c the collection whose elements are to be placed into this list
Throws:
java.lang.NullPointerException if the specified collection is null
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    
Returns the first element in this list.

Returns:
the first element in this list
Throws:
NoSuchElementException if this list is empty
    public E getFirst() {
        if (==0)
            throw new NoSuchElementException();
        return ..;
    }

    
Returns the last element in this list.

Returns:
the last element in this list
Throws:
NoSuchElementException if this list is empty
    public E getLast()  {
        if (==0)
            throw new NoSuchElementException();
        return ..;
    }

    
Removes and returns the first element from this list.

Returns:
the first element from this list
Throws:
NoSuchElementException if this list is empty
    public E removeFirst() {
        return remove(.);
    }

    
Removes and returns the last element from this list.

Returns:
the last element from this list
Throws:
NoSuchElementException if this list is empty
    public E removeLast() {
        return remove(.);
    }

    
Inserts the specified element at the beginning of this list.

Parameters:
e the element to add
    public void addFirst(E e) {
        addBefore(e.);
    }

    
Appends the specified element to the end of this list.

This method is equivalent to add(java.lang.Object).

Parameters:
e the element to add
    public void addLast(E e) {
        addBefore(e);
    }

    
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:
o element whose presence in this list is to be tested
Returns:
true if this list contains the specified element
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

    
Returns the number of elements in this list.

Returns:
the number of elements in this list
    public int size() {
        return ;
    }

    
Appends the specified element to the end of this list.

This method is equivalent to addLast(java.lang.Object).

Parameters:
e element to be appended to this list
Returns:
true (as specified by Collection.add(java.lang.Object))
    public boolean add(E e) {
        addBefore(e);
        return true;
    }

    
Removes the first occurrence of the specified element from this list, if it is present. If this 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). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).

Parameters:
o element to be removed from this list, if present
Returns:
true if this list contained the specified element
    public boolean remove(Object o) {
        if (o==null) {
            for (Entry<E> e = .e != e = e.next) {
                if (e.element==null) {
                    remove(e);
                    return true;
                }
            }
        } else {
            for (Entry<E> e = .e != e = e.next) {
                if (o.equals(e.element)) {
                    remove(e);
                    return true;
                }
            }
        }
        return false;
    }

    
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. (Note that this will occur if the specified collection is this list, and it's nonempty.)

Parameters:
c collection containing elements to be added to this list
Returns:
true if this list changed as a result of the call
Throws:
java.lang.NullPointerException if the specified collection is null
    public boolean addAll(Collection<? extends E> c) {
        return addAll(c);
    }

    
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:
index index at which to insert the first element from the specified collection
c collection containing elements to be added to this list
Returns:
true if this list changed as a result of the call
Throws:
java.lang.IndexOutOfBoundsException
java.lang.NullPointerException if the specified collection is null
    public boolean addAll(int indexCollection<? extends E> c) {
        if (index < 0 || index > )
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+);
        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew==0)
            return false;
        ++;
        Entry<E> successor = (index== ?  : entry(index));
        Entry<E> predecessor = successor.previous;
        for (int i=0; i<numNewi++) {
            Entry<E> e = new Entry<E>((E)a[i], successorpredecessor);
            predecessor.next = e;
            predecessor = e;
        }
        successor.previous = predecessor;
         += numNew;
        return true;
    }

    
Removes all of the elements from this list.
    public void clear() {
        Entry<E> e = .;
        while (e != ) {
            Entry<E> next = e.next;
            e.next = e.previous = null;
            e.element = null;
            e = next;
        }
        . = . = ;
         = 0;
        ++;
    }
    // Positional Access Operations

    
Returns the element at the specified position in this list.

Parameters:
index index of the element to return
Returns:
the element at the specified position in this list
Throws:
java.lang.IndexOutOfBoundsException
    public E get(int index) {
        return entry(index).;
    }

    
Replaces the element at the specified position in this list with the specified element.

Parameters:
index index of the element to replace
element element to be stored at the specified position
Returns:
the element previously at the specified position
Throws:
java.lang.IndexOutOfBoundsException
    public E set(int index, E element) {
        Entry<E> e = entry(index);
        E oldVal = e.element;
        e.element = element;
        return oldVal;
    }

    
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:
index index at which the specified element is to be inserted
element element to be inserted
Throws:
java.lang.IndexOutOfBoundsException
    public void add(int index, E element) {
        addBefore(element, (index== ?  : entry(index)));
    }

    
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:
index the index of the element to be removed
Returns:
the element previously at the specified position
Throws:
java.lang.IndexOutOfBoundsException
    public E remove(int index) {
        return remove(entry(index));
    }

    
Returns the indexed entry.
    private Entry<E> entry(int index) {
        if (index < 0 || index >= )
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+);
        Entry<E> e = ;
        if (index < ( >> 1)) {
            for (int i = 0; i <= indexi++)
                e = e.next;
        } else {
            for (int i = i > indexi--)
                e = e.previous;
        }
        return e;
    }
    // Search Operations

    
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the 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:
o element to search for
Returns:
the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element
    public int indexOf(Object o) {
        int index = 0;
        if (o==null) {
            for (Entry e = .e != e = e.next) {
                if (e.element==null)
                    return index;
                index++;
            }
        } else {
            for (Entry e = .e != e = e.next) {
                if (o.equals(e.element))
                    return index;
                index++;
            }
        }
        return -1;
    }

    
Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the 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:
o element to search for
Returns:
the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element
    public int lastIndexOf(Object o) {
        int index = ;
        if (o==null) {
            for (Entry e = .e != e = e.previous) {
                index--;
                if (e.element==null)
                    return index;
            }
        } else {
            for (Entry e = .e != e = e.previous) {
                index--;
                if (o.equals(e.element))
                    return index;
            }
        }
        return -1;
    }
    // Queue operations.

    
Retrieves, but does not remove, the head (first element) of this list.

Returns:
the head of this list, or null if this list is empty
Since:
1.5
    public E peek() {
        if (==0)
            return null;
        return getFirst();
    }

    
Retrieves, but does not remove, the head (first element) of this list.

Returns:
the head of this list
Throws:
NoSuchElementException if this list is empty
Since:
1.5
    public E element() {
        return getFirst();
    }

    
Retrieves and removes the head (first element) of this list

Returns:
the head of this list, or null if this list is empty
Since:
1.5
    public E poll() {
        if (==0)
            return null;
        return removeFirst();
    }

    
Retrieves and removes the head (first element) of this list.

Returns:
the head of this list
Throws:
NoSuchElementException if this list is empty
Since:
1.5
    public E remove() {
        return removeFirst();
    }

    
Adds the specified element as the tail (last element) of this list.

Parameters:
e the element to add
Returns:
true (as specified by Queue.offer(java.lang.Object))
Since:
1.5
    public boolean offer(E e) {
        return add(e);
    }
    // Deque operations
    
Inserts the specified element at the front of this list.

Parameters:
e the element to insert
Returns:
true (as specified by Deque.offerFirst(java.lang.Object))
Since:
1.6
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

    
Inserts the specified element at the end of this list.

Parameters:
e the element to insert
Returns:
true (as specified by Deque.offerLast(java.lang.Object))
Since:
1.6
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

    
Retrieves, but does not remove, the first element of this list, or returns null if this list is empty.

Returns:
the first element of this list, or null if this list is empty
Since:
1.6
    public E peekFirst() {
        if (==0)
            return null;
        return getFirst();
    }

    
Retrieves, but does not remove, the last element of this list, or returns null if this list is empty.

Returns:
the last element of this list, or null if this list is empty
Since:
1.6
    public E peekLast() {
        if (==0)
            return null;
        return getLast();
    }

    
Retrieves and removes the first element of this list, or returns null if this list is empty.

Returns:
the first element of this list, or null if this list is empty
Since:
1.6
    public E pollFirst() {
        if (==0)
            return null;
        return removeFirst();
    }

    
Retrieves and removes the last element of this list, or returns null if this list is empty.

Returns:
the last element of this list, or null if this list is empty
Since:
1.6
    public E pollLast() {
        if (==0)
            return null;
        return removeLast();
    }

    
Pushes an element onto the stack represented by this list. In other words, inserts the element at the front of this list.

This method is equivalent to addFirst(java.lang.Object).

Parameters:
e the element to push
Since:
1.6
    public void push(E e) {
        addFirst(e);
    }

    
Pops an element from the stack represented by this list. In other words, removes and returns the first element of this list.

This method is equivalent to removeFirst().

Returns:
the element at the front of this list (which is the top of the stack represented by this list)
Throws:
NoSuchElementException if this list is empty
Since:
1.6
    public E pop() {
        return removeFirst();
    }

    
Removes the first occurrence of the specified element in this list (when traversing the list from head to tail). If the list does not contain the element, it is unchanged.

Parameters:
o element to be removed from this list, if present
Returns:
true if the list contained the specified element
Since:
1.6
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

    
Removes the last occurrence of the specified element in this list (when traversing the list from head to tail). If the list does not contain the element, it is unchanged.

Parameters:
o element to be removed from this list, if present
Returns:
true if the list contained the specified element
Since:
1.6
    public boolean removeLastOccurrence(Object o) {
        if (o==null) {
            for (Entry<E> e = .e != e = e.previous) {
                if (e.element==null) {
                    remove(e);
                    return true;
                }
            }
        } else {
            for (Entry<E> e = .e != e = e.previous) {
                if (o.equals(e.element)) {
                    remove(e);
                    return true;
                }
            }
        }
        return false;
    }

    
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:
index index of the first element to be returned from the list-iterator (by a call to next)
Returns:
a ListIterator of the elements in this list (in proper sequence), starting at the specified position in the list
Throws:
java.lang.IndexOutOfBoundsException
See also:
List.listIterator(int)
    public ListIterator<E> listIterator(int index) {
        return new ListItr(index);
    }
    private class ListItr implements ListIterator<E> {
        private Entry<E> lastReturned = ;
        private Entry<E> next;
        private int nextIndex;
        private int expectedModCount = ;
        ListItr(int index) {
            if (index < 0 || index > )
                throw new IndexOutOfBoundsException("Index: "+index+
                                                    ", Size: "+);
            if (index < ( >> 1)) {
                 = .;
                for (=0; <index++)
                     = .;
            } else {
                 = ;
                for (=>index--)
                     = .;
            }
        }
        public boolean hasNext() {
            return  != ;
        }
        public E next() {
            checkForComodification();
            if ( == )
                throw new NoSuchElementException();
             = ;
             = .;
            ++;
            return .;
        }
        public boolean hasPrevious() {
            return  != 0;
        }
        public E previous() {
            if ( == 0)
                throw new NoSuchElementException();
             =  = .;
            --;
            checkForComodification();
            return .;
        }
        public int nextIndex() {
            return ;
        }
        public int previousIndex() {
            return -1;
        }
        public void remove() {
            checkForComodification();
            Entry<E> lastNext = .;
            try {
                LinkedList.this.remove();
            } catch (NoSuchElementException e) {
                throw new IllegalStateException();
            }
            if (==)
                 = lastNext;
            else
                --;
             = ;
            ++;
        }
        public void set(E e) {
            if ( == )
                throw new IllegalStateException();
            checkForComodification();
            . = e;
        }
        public void add(E e) {
            checkForComodification();
             = ;
            addBefore(e);
            ++;
            ++;
        }
        final void checkForComodification() {
            if ( != )
                throw new ConcurrentModificationException();
        }
    }
    private static class Entry<E> {
        E element;
        Entry<E> next;
        Entry<E> previous;
        Entry(E elementEntry<E> nextEntry<E> previous) {
            this. = element;
            this. = next;
            this. = previous;
        }
    }
    private Entry<E> addBefore(E eEntry<E> entry) {
        Entry<E> newEntry = new Entry<E>(eentryentry.previous);
        newEntry.previous.next = newEntry;
        newEntry.next.previous = newEntry;
        ++;
        ++;
        return newEntry;
    }
    private E remove(Entry<E> e) {
        if (e == )
            throw new NoSuchElementException();
        E result = e.element;
        e.previous.next = e.next;
        e.next.previous = e.previous;
        e.next = e.previous = null;
        e.element = null;
        --;
        ++;
        return result;
    }

    

Since:
1.6
    public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }

    
Adapter to provide descending iterators via ListItr.previous
    private class DescendingIterator implements Iterator {
        final ListItr itr = new ListItr(size());
        public boolean hasNext() {
            return .hasPrevious();
        }
        public E next() {
            return .previous();
        }
        public void remove() {
            .remove();
        }
    }

    
Returns a shallow copy of this LinkedList. (The elements themselves are not cloned.)

Returns:
a shallow copy of this LinkedList instance
    public Object clone() {
        LinkedList<E> clone = null;
        try {
            clone = (LinkedList<E>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }
        // Put clone into "virgin" state
        clone.header = new Entry<E>(nullnullnull);
        clone.header.next = clone.header.previous = clone.header;
        clone.size = 0;
        clone.modCount = 0;
        // Initialize clone with our elements
        for (Entry<E> e = .e != e = e.next)
            clone.add(e.element);
        return clone;
    }

    
Returns an array containing all of the elements in this list in proper sequence (from first to last element).

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

This method acts as bridge between array-based and collection-based APIs.

Returns:
an array containing all of the elements in this list in proper sequence
    public Object[] toArray() {
        Object[] result = new Object[];
        int i = 0;
        for (Entry<E> e = .e != e = e.next)
            result[i++] = e.element;
        return result;
    }

    
Returns an array containing all of the elements in this list in proper sequence (from first to last element); 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 list 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.)

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

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

     String[] y = x.toArray(new String[0]);
Note that toArray(new Object[0]) is identical in function to toArray().

Parameters:
a the 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.
Returns:
an array containing the elements of the list
Throws:
java.lang.ArrayStoreException if the runtime type of the specified array is not a supertype of the runtime type of every element in this list
java.lang.NullPointerException if the specified array is null
    public <T> T[] toArray(T[] a) {
        if (a.length < )
            a = (T[])java.lang.reflect.Array.newInstance(
                                a.getClass().getComponentType(), );
        int i = 0;
        Object[] result = a;
        for (Entry<E> e = .e != e = e.next)
            result[i++] = e.element;
        if (a.length > )
            a[] = null;
        return a;
    }
    private static final long serialVersionUID = 876323262645176354L;

    
Save the state of this LinkedList instance to a stream (that is, serialize it).

SerialData:
The size of the list (the number of elements it contains) is emitted (int), followed by all of its elements (each an Object) in the proper order.
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();
        // Write out size
        s.writeInt();
        // Write out all elements in the proper order.
        for (Entry e = .e != e = e.next)
            s.writeObject(e.element);
    }

    
Reconstitute this LinkedList instance from a stream (that is deserialize it).
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOExceptionClassNotFoundException {
        // Read in any hidden serialization magic
        s.defaultReadObject();
        // Read in size
        int size = s.readInt();
        // Initialize header
         = new Entry<E>(nullnullnull);
        . = . = ;
        // Read in all elements in the proper order.
        for (int i=0; i<sizei++)
            addBefore((E)s.readObject(), );
    }
New to GrepCode? Check out our FAQ X