LinkedList in Java

  • LinkedList class extends AbstractSequentialList class and implements List Interface.
  • The LinkedList class provides methods to get, remove and insert an element at the beginning and end of the list.
  • The LinkedList can be used as stack, queue, or double-ended queue.
  • LinkedList is not synchronized and hence it must be synchronized externally when it is using multi - threaded program.
  • The LinkedList will return Iterator and ListIterator method.
  • To create LinkedList, you can use add, addFirst and addLast methods.
  • To get elements from the List, you can use get, getFirst and getLast methods.
  • To set element’s value, you can use set method.
  • To remove elements, you can use remove, removeFirst and removeLast methods.
  • To remove all the elements, you can use clear() method.
The following table demonstrates the constructors of LinkedList and corresponding methods.

Constructor
Meaning
LinkedList()
Constructs LinkedList Object.
LinkedList(Collection c)
Constructs a list containing the elements of the given collection.

The following program shows a simple use of LinkedList. 

Example:

/**
From SimpleLinkedList.java
*/

import java.util.LinkedList;

/**
 *
 * @author JavaHotSpot
 */

public class SimpleLinkedList
{
  public static void main(String args[])
  {
      LinkedList list = new LinkedList();
      list.add("Book2");
      list.add("Book3");
      list.add("Book4");
      list.add("Book5");
      list.addFirst("Book1");
      list.addLast("Book6");
      System.out.println("The elements are"+"\n"+list);
      list.removeFirst();
      list.removeLast();
      System.out.println("After removing First and Last element"+"\n"+"Now elements are"+"\n"+list);

      list.set(0, "One");
      list.set(1, "Two");
      list.set(2, "Three");
      list.set(3, "Four");
       System.out.println("Setting the elements "+"\n"+"Now elements are"+"\n"+list);
  }
}

Output:
The elements are
[Book1, Book2, Book3, Book4, Book5, Book6]
After removing First and Last element
Now elements are
[Book2, Book3, Book4, Book5]
Setting the elements
Now elements are