LinkedList is a part of the Java Collection Framework and is present in the java.util package. It implements a doubly-linked list data structure where elements are not stored in contiguous memory. Each node contains three parts: the data, a reference to the next node, and a reference to the previous node
- Dynamic Size: LinkedList grows or shrinks dynamically at runtime.
- Maintains Insertion Order: Elements are stored in the order they are added.
- Allows Duplicates: Duplicate elements are allowed.
- Not Synchronized: By default, LinkedList is not thread-safe. To make Thread-safe use of Collections.synchronizedList().
- Efficient Insertion/Deletion: Adding or removing elements at the beginning or middle is faster compared to ArrayList.
import java.util.LinkedList;
public class Geeks {
public static void main(String[] args){
// Creating a LinkedList
LinkedList<String> l = new LinkedList<String>();
// Adding elements to the LinkedList using add() method
l.add("One");
l.add("Two");
l.add("Three");
l.add("Four");
l.add("Five");
System.out.println(l);
}
}
Output
[One, Two, Three, Four, Five]
Explanation:
- Creates an empty LinkedList of Strings.
- Adds elements "One" to "Five" using the add() method.
- Prints the LinkedList showing elements in insertion order: [One, Two, Three, Four, Five].
Note: LinkedList nodes cannot be accessed directly by index; elements must be accessed by traversing from the head.
Hierarchy of LinkedList
It implements the List and Deque interfaces, both of which are sub-interfaces of the Collection Interface.