Java LinkedList class
The LinkedList class extends AbstractSequentialList and implements the List, Deque, and Queue interfaces. It provides a linked-list data structure. LinkedList is a generic class that has this declaration
Here, M specifies the type of objects that the list will hold. LinkedList has the two constructors shown here:
-
LinkedList( )
-
LinkedList(Collectionc)
-
The first constructor builds an empty linked list.
-
The second constructor builds a linked list that is initialized with the elements of the collection c.
-
This is the subject to study in data structures, Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list data structure. It inherits the AbstractList class and implements List and Deque interfaces.
The important points about Java LinkedList are:
-
Java LinkedList class is nonsynchronized.
-
In the Java LinkedList class, manipulation is fast because no shifting needs to occur.
-
Java LinkedList class maintains insertion order.
-
Java LinkedList class can be used as a list, stack, or queue.
-
Java LinkedList class can contain duplicate elements.
Example -
package javaLearnings;
import java.util.LinkedList;
// Demonstrate LinkedList.
public class Main {
public static void main(String args[]) {
// Create a linked list.
LinkedList ll = new LinkedList();
// Add elements to the linked list.
ll.add("M");
ll.add("U");
ll.add("K");
ll.add("U");
ll.add("L");
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.
String val = ll.get(2);
ll.set(2, val + " Changed");
System.out.println("ll after change: " + ll);
}
}
|
Output -
LinkedList Methods -
We have already seen the use of these methods in previous example -