Java LinkedList : Collection Class



LinkedList class :

  1. LinkedList allows duplicate elements in it.
  2. LinkedList class extends AbstractList class and implements List and Deque interface.
  3. LinkedList maintains insertion order.
  4. LinkedList can be iterated sequencially not in random fashion like ArrayList.
  5. LinkedList is faster than that of ArrayList as no shifting will be required in case of insertion and deletion operations
  6. LikedList class uses doubly linked list to store the elements
  7. LikedList class can be used as list,stack and queue

Lets create an LinkedList using following line of code -

Example #1 : Create Linked List

package com.c4learn.set;
import java.util.LinkedList;
public class LinkedListExamples {
  public static void main(String[] args) {
    LinkedList<String> lList = new LinkedList<String>();
    lList.add("B");
    lList.add("C");
    lList.add("D");
    lList.add("E");
    System.out.println("Initial Linked List : " + lList);
  }
}

Output :

Initial Linked List : [B, C, D, E]

In the above example, we have created an Linked list using the following line -

LinkedList<String> lList = new LinkedList<String>();

The above linked list is used to store the String. We need to add some objects of type String in the linked list using following line of code -

lList.add("B");
lList.add("C");
lList.add("D");
lList.add("E");

Now in order to print the linked list, we just need to provide linked list name as parameter to print method.

System.out.println("Initial Linked List : " + lList);

Example #2 : Using Iteration to Print ArrayList

Now in the above program, we have learnt to create an arraylist. Now we need to access each element of ArrayList and need to print each element seperatly.

package com.c4learn.linkedlist;
import java.util.Iterator;
import java.util.LinkedList;
public class LinkedListExamples {
  public static void main(String[] args) {
    LinkedList<String> lList = new LinkedList<String>();
    lList.add("B");
    lList.add("C");
    lList.add("D");
    lList.add("E");
    Iterator<String> itr = lList.iterator();
    while (itr.hasNext()) {
        String str = (String) itr.next();
        System.out.println(str);
      }
  }
}

Output :

B
C
D
E