Updates
  • Starting New Weekday Batch for Java Full Stack Developer on 24th June 2024 @ 02:00 PM to 04:00 PM
  • Starting New Weekend Batch for Java Full Stack Developer on 06th July 2024 @ 11:00 AM to 02:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 08th July 2024 @ 04:00 PM to 06:00 PM
  • Starting New Weekday Batch for Java Full Stack Developer on 29th July 2024 @ 10:00 AM to 12:00 PM
Join Course

LinkedList

LinkedList is a class available in the java.util package because it implements the java.util.List interface, making it a List type collection.

Linked List important points:

1. LinkedList stores elements using nodes. A node is a memory allocation that stores data and the reference of the next node.
2. Duplicate data can be stored in LinkedList.
3. Different types of data can be stored, similar to ArrayList.
4. Random access is not allowed in LinkedList; elements must be accessed sequentially.
5. Elements can be accessed using iterators and ListIterators.
6. LinkedList class methods are not synchronized in nature.
7. LinkedList class implements java.io.Serializable and java.lang.Cloneable, making it eligible for serialization and cloning, respectively.

            
importjava.util.ArrayList;
importjava.util.Comparator;
importjava.util.Iterator;
importjava.util.LinkedList;
importjava.util.ListIterator;
publicclass JTC {
   publicstaticvoid main(String[] args) {
      LinkedListl1 = newLinkedList();
      l1.add("10");
      l1.add("Hello");
      l1.add(12.34 f);
      l1.add(13.678);
      l1.add(true);
      l1.add('A');
      l1.add(new JTC());
      l1.add(null);
      System.out.println("l1 :- " + l1);
      // Traversing elements using Iterator.
      Iteratoriterator = l1.iterator();
      while (iterator.hasNext()) {
         System.out.print(iterator.next() + " ");
      }
      // Traversing Element using List-Iterator in forward order.
      System.out.print("\nForward :- ");
      ListIteratoriterator1 = l1.listIterator();
      while (iterator1.hasNext()) {
         System.out.print(iterator1.next() + " ");
      }
      // Traversing Element using List-Iterator in reverse order.
      System.out.print("\nReverse :- ");
      while (iterator1.hasPrevious()) {
         System.out.print(iterator1.previous() + " ");
      }
   }
}
    l1 :- [10, Hello, 12.34, 13.678, true, A, com.P1.JTC@36aa7bc2, null]
    10 Hello 12.34 13.678 true A com.P1.JTC@36aa7bc2 null 
    Forward :- 10 Hello 12.34 13.678 true A com.P1.JTC@36aa7bc2 null 
    Reverse :- null com.P1.JTC@36aa7bc2 A true 13.678 12.34 Hello 10 
            

In this example, we are creating a LinkedList, which involves creating an object of the java.util.LinkedList class and adding elements of different types using the add() method of the java.util.LinkedList class.
In the next section, we traverse the LinkedList using an iterator. As seen in the above example, we invoke the iterator() method of the java.util.LinkedList class, which returns an object of the java.util.Iterator interface type. Finally, we use the hasNext() and next() methods to iterate through the LinkedList.
In the last section of the above example, we access the LinkedList in both forward and reverse order. First, we create an object of the List Iterator type by invoking the listIterator() method of the java.util.LinkedList class. Then, using hasNext() and next() methods, we traverse the LinkedList in forward order. Similarly, using hasPrevious() and previous() methods, we traverse the list in reverse order.

Important Constructor of java.util.LinkedList class:

1. public java.util.LinkedList(): This is the default constructor of the java.util.LinkedList class. When we use the default constructor to create an object of the java.util.LinkedList class, we obtain an empty LinkedList.

2. public java.util.LinkedList(java.util.Collection<? extends E>); We use this constructor to create a LinkedList that contains all the elements of the collection passed as an argument.

            
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
public class JTC {
  public static void main(String[] args) {
    // Creating empty linked list using default constructor.
    LinkedList l1 = new LinkedList();
    System.out.println("l1.size :- " + l1.size());
    System.out.println("l1 :- " + l1);
    ArrayList al1 = new ArrayList();
    al1.add(101);
    al1.add("Hello");
    al1.add(true);
    al1.add(12.34 f);
    LinkedList l2 = new LinkedList < > (al1);
    System.out.println("l2.size :- " + l2.size());
    System.out.println("l2 :- " + l2);
  }
}
        
    l1.size :- 0
   l1 :- []
   l2.size :- 4
   l2 :- [101, Hello, true, 12.34]
            
Important member of java.util.LinkedList class:

1. public boolean add(E) :- It appends elements to the end of the current linked list and returns true.

2. public void add(int, E) :- Inserts the specified element at the specified position in this list and shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

3. public boolean addAll(java.util.Collection<? extends E>) :- We use the addAll() method to add all the elements into the current working linked list, and the order of the elements will be the same as in the collection.

            
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
public class JTC {
   public static void main(String[] args) {
      LinkedList l1 = new LinkedList();
      l1.add("E1");
      l1.add("E2");
      ArrayList al1 = new ArrayList();
      al1.add("Hello");
      al1.add(102);
      al1.add(true);
      al1.add("JTC");
      l1.addAll(al1);
      System.out.println("l1 :- " + l1);
   }
}
        
   l1 :- [E1, E2, Hello, 102, true, JTC]
            

4. public boolean addAll(int, java.util.Collection<? extends E>) :- It adds all the elements into the current linked list at the specified position, and the order of the elements will be the same as in the collection.

            
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
public class JTC {
   public static void main(String[] args) {
      LinkedList l1 = new LinkedList();
      l1.add("E1");
      l1.add("E2");
      ArrayList al1 = new ArrayList();
      al1.add("Hello");
      al1.add(102);
      al1.add(true);
      al1.add("JTC");
      l1.addAll(1, al1);
      System.out.println("l1 :- " + l1);
   }
}
   l1 :- [E1, Hello, 102, true, JTC, E2]
            

Note: When we are performing any operation on a linked list, we cannot add any elements into the same linked list in between the operation; otherwise, we will get a java.util.ConcurrentModificationException.

            
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
public class JTC {
   public static void main(String[] args) {
      LinkedList l1 = new LinkedList();
      l1.add(101);
      l1.add(102);
      l1.add(103);
      l1.add(104);
      l1.add(105);
      Iterator i1 = l1.iterator();
      while (i1.hasNext()) {
         System.out.println(i1.next());
         l1.add(606);
      }
   }
}
   101
   Exception in thread "main" java.util.ConcurrentModificationException
   at java.base/java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:970)
   at java.base/java.util.LinkedList$ListItr.next(LinkedList.java:892)
   at com.P1.JTC.main(JTC.java:22)
            

5. public E get(int) :- It returns the element at the specified position from the current linked list. If the index is not in the current linked list, we get an ArrayIndexOutOfBoundsException exception at runtime.

            
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
public class JTC {
   public static void main(String[] args) {
      LinkedList l1 = new LinkedList();
      l1.add(101);
      l1.add(102);
      l1.add(103);
      l1.add(104);
      l1.add(105);
      System.out.println("l1.get(0) :- " + l1.get(0));
      System.out.println("l1.get(100) :- " + l1.get(100));
   }
}
   l1.get(0) :- 101
   Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: -100, Size: 5
   at java.base/java.util.LinkedList.checkElementIndex(LinkedList.java:559)
   at java.base/java.util.LinkedList.get(LinkedList.java:480)
   at com.P1.JTC.main(JTC.java:20)
            

6. public E set(int, E) :- This method is basically used to set or update the element at the specified position and returns the same element. If we try to update a position that is not in the current linked list, we get an ArrayIndexOutOfBoundsException.

            
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
public class JTC {
   public static void main(String[] args) {
      LinkedList l1 = new LinkedList();
      l1.add(101);
      l1.add(102);
      l1.add(103);
      l1.add(104);
      l1.add(105);
      System.out.println("l1 :- " + l1);
      System.out.println(l1.set(3, 67) + " is set into the l1.");
      System.out.println("l1 :- " + l1);
      System.out.println(l1.set(5, 8));

   }
}
   l1 :- [101, 102, 103, 104, 105]
   104 is set into the l1.
   l1 :- [101, 102, 103, 67, 105]
   Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
   at java.base/java.util.LinkedList.checkElementIndex(LinkedList.java:559)
   at java.base/java.util.LinkedList.set(LinkedList.java:494)
   at com.P1.JTC.main(JTC.java:25)
            

7. public java.util.Iterator<E> descendingIterator() :- It returns an iterator type object that contains elements in reverse order.

            
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
public class JTC {
   public static void main(String[] args) {
      LinkedList l1 = new LinkedList();
      l1.add(101);
      l1.add(102);
      l1.add(103);
      l1.add(104);
      l1.add(105);
      Iterator i1 = l1.descendingIterator();
      while (i1.hasNext()) {
         System.out.print(i1.next() + " ");
      }
   }
}
   105 104 103 102 101