The LinkedList class of the Java collections framework provides the functionality of the linked list data structure (doubly linkedlist).
Each element in a linked list is known as a node. It consists of 3 fields:
Prev - stores an address of the previous element in the list. It is null for the first element
Next - stores an address of the next element in the list. It is null for the last element
Data - stores the actual data
- Syntax for creating a LinkedList:
LinkedList<Type> linkedList = new LinkedList<>();
Here, Type indicates the type of a linked list. For example,
// create Integer type linked list
LinkedList<Integer> linkedList = new LinkedList<>();
// create String type linked list
LinkedList<String> linkedList = new LinkedList<>();
- Example Program to create LinkedList:
import java.util.LinkedList;
class Main {
public static void main(String[] args){
// create linkedlist
LinkedList<String> animals = new LinkedList<>();
// Add elements to LinkedList
animals.add("Dog");
animals.add("Cat");
animals.add("Parrot");
System.out.println("LinkedList: " + animals);
}
}
OUTPUT:
LinkedList: [Dog, Cat, Parrot]
Top comments (0)