Java LinkedList Documentation - Complete Guide

Comments · 1 Views

Implements List and Deque interfaces

Java provides the LinkedList class as a part of the java linkedlist documentation . It implements the List and Deque interfaces, allowing for dynamic memory allocation and efficient insertions and deletions. Unlike arrays, a linked list consists of nodes where each node contains data and a reference to the next node in the sequence.

Features of LinkedList

Allows duplicate elements

Maintains insertion order

Supports efficient addition and removal operations

Can be used as a stack, queue, or deque

How to Create a LinkedList

To use LinkedList, import java.util.LinkedList and instantiate it as follows
import java.util.LinkedList;

public class LinkedListExample {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("LinkedList: " + list);
}
}
Adding Elements to LinkedList

You can add elements using:

add(E e): Appends an element at the end

add(int index, E e): Inserts at a specific position

addFirst(E e): Adds element at the head

addLast(E e): Adds element at the tail

Example:
list.addFirst("Mango");
list.addLast("Orange");
Removing Elements

Use the following methods to remove elements:

remove(): Removes the first element

remove(int index): Removes element at a specific index

removeFirst() / removeLast(): Removes first/last element

Example:
list.remove(1); // Removes the second element
list.removeFirst();
Accessing Elements

Retrieve elements using:

get(int index): Fetches element at the specified index

getFirst() / getLast(): Retrieves the first/last element


System.out.println("First Element: " + list.getFirst());
System.out.println("Element at index 2: " + list.get(2));
Conclusion

Java LinkedList is a versatile data structure that provides efficient insertions and deletions. It can be used as a list, queue, or stack, making it a powerful tool for various applications.


Accessing Elements

Retrieve elements using:

get(int index): Fetches element at the specified index

getFirst() / getLast(): Retrieves the first/last element


[1]: https://docs.vultr.com/java/examples/implement-linkedlist

Comments