LinkedList Class in java


The LinkedList class extends Abstract SequentialList and implements the List interface. It provides a linked-list data structure.


Constructor:  

S.N. Constructor & Description
LinkedList()
This constructor builds an empty linked list.
LinkedList(Collection c)
This constructor builds a linked list that is initialized with elements of the collection c.     

Methods:

S.N. Methods with Description
void add(int index,Object element)
Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is out of range.
boolean addAll(Collection c)
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. Throws NullPointerExeception if the specified collection is null.
void addFirst(Object o)
Inserts the given element at the beginning of this list.
void addLast(Object o)
Appends the given element to the end of this list.
void clear()
Removes all of the elements from this list.
Object getFirst()
Returns the first element in this list. Throws NoSuchElementException if this list is empty.
Object getLast()
Returns the last element in this list. Throws NoSuchElementException if this list is empty.
int size()
Returns the number of elements in this list.


Example:

import java.util.*;

public class LinkedListDemo
{
         public static void main(String args[])
         {
               // create a linked list
               LinkedList ll = new LinkedList();
              // add elements to the linked list
              ll.add("F");
              ll.add("B");
              ll.add("D");
              ll.add("E");
              ll.add("C");
              ll.addLast("Z");
              ll.addFirst("A");
              ll.add(1,"A2");
              System.out.println("Original contents of ll:"+ll);

              // remove elements from the linked list
             ll.remove("F");
             ll.remove(2);
             System.out.println("Contents of ll after deletion:"+ll);

             // remove first and last elements 
            ll.removeFirst();
            ll.removeLast();
            System.out.println("ll after deleting first and last:"+ll);

           // get and set a value
          Object val=ll.get(2);
          ll.set(2,(String) val + "Changed");
          System.out.println("ll after change:"+ll);
         }
}