What is a LinkedList in Java?

What is a LinkedList?

A LinkedList is a special type of data structure that we can use to store a collection of elements in a connected form.

An ArrayList keeps all its elements in one continuous memory block, but a LinkedList stores elements in separate nodes. Each node holds two main parts:

  • The data (actual value and object)
  • A reference (link) to the text node in the sequence

Because a LinkedList is like a chain of boxes, where each box knows where the next one is kept.

How LinkedList Works?

Suppose we have several students standing in line, and each line is holding a paper with:

  • Their own name written on it (the data)
  • A note showing who is standing next (the reference)

If you add a new student in the middle, they point to the next person, and the previous one updates their note; no one else needs to move!

That’s how a LinkedList manages insertions and deletions.

Why Use a LinkedList in Java?

  • Part of Java Collection Framework: It belongs to the java.util package and implements both the List and Deque interfaces. That means you can use it as a list, queue, or even a stack depending on your needs.
  • Doubly Linked Structure: Each node in Java’s LinkedList has links to both the previous and the next node. This allows you to move forward and backwards through the list easily.
  • Memory Usage: Each node keeps extra references (to next and previous), so LinkedList uses more memory than ArrayList.

How to Use LinkedList in Java

1) Import the LinkedList Class

First, we will import LinkedList from java.util package.

import java.util.LinkedList;
  • The java.util package contains all the collection classes like ArrayList, HashMap, and LinkedList.

2) Creating a LinkedList

You can create a LinkedList that stores elements of a specific data type using generics. This ensures your list only contains elements of that type and avoids type errors.

Example 1 – Creating a LinkedList of Strings:

LinkedList<String> list = new LinkedList<>();
  • Now, this list can only store String values (like city names).

Example 2 – Creating a LinkedList of Integers:

LinkedList<Integer> marks = new LinkedList<>();

//This list can store integer values, such as marks or scores.

3) Adding Elements to LinkedList

You can easily add elements to the list using the add() method.

cities.add("Delhi");
cities.add("Mumbai");
cities.add("Pune");

You can also add elements at the beginning or end of the list using the following methods:

cities.addFirst("Ahmedabad");
cities.addLast("Bangalore");

Now your list looks like this:

[Ahmedabad, Delhi, Mumbai, Pune, Bangalore]

4) Creating and Initializing a LinkedList with Values

Sometimes you want to create a list with predefined values instead of adding them one by one. You can do that using the Arrays.asList() method:

import java.util.Arrays;
import java.util.LinkedList;

LinkedList<Integer> numbers = new LinkedList<>(Arrays.asList(10, 20, 30, 40));

Here:

  • Arrays.asList() quickly creates a list of values.
  • The LinkedList constructor copies those values into a new LinkedList.

Output:

[10, 20, 30, 40]

5) Displaying Elements

We can easily print all elements of our LinkedList like this:

System.out.println("Cities: " + cities);
System.out.println("Numbers: " + numbers);

Output:

Cities: [Ahmedabad, Delhi, Mumbai, Pune, Bangalore]
Numbers: [10, 20, 30, 40]

Common Methods of LinkedList

MethodDescription
add(E e)Adds an element to the end of the list.
addFirst(E e)Adds an element at the beginning of the list.
addLast(E e)Adds an element at the end of the list.
remove()Removes and returns the first element of the list.
removeFirst()Removes the first element of the list.
removeLast()Removes the last element of the list.
get(int index)Retrieves the element at the specified index.
size()Returns the number of elements in the list.
peek()Retrieves but does not remove the first element.
contains(Object o)Checks if the list contains the specified element.
clear()Removes all elements from the list.

Examples of Using LinkedList

In this proper example, we will learn how to create a LinkedList, add elements, add or remove elements from both ends, and display the final list.

import java.util.LinkedList;

public class LinkedListExample {
public static void main(String[] args) {
// Create a LinkedList to store fruits
LinkedList<String> fruits = new LinkedList<>();

// Add elements to the list
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

System.out.println("Fruits: " + fruits);

// Add an element at the beginning
fruits.addFirst("Orange");
System.out.println("After Adding First: " + fruits);

// Add an element at the end
fruits.addLast("Grapes");
System.out.println("After Adding Last: " + fruits);

// Remove the first element
fruits.removeFirst();
System.out.println("After Removing First: " + fruits);

// Remove the last element
fruits.removeLast();
System.out.println("After Removing Last: " + fruits);
}
}

Output:

Fruits: [Apple, Banana, Cherry]
After Adding First: [Orange, Apple, Banana, Cherry]
After Adding Last: [Orange, Apple, Banana, Cherry, Grapes]
After Removing First: [Apple, Banana, Cherry, Grapes]
After Removing Last: [Apple, Banana, Cherry]
  • You can see that, each time you add or remove an element, LinkedList automatically updates the links between its nodes.

2. Traversing a LinkedList

You can go through (or traverse) all elements of a LinkedList using different loops.

Using a For-Each Loop

This is the simplest and cleanest way to display all elements:

for (String fruit : fruits) {
System.out.println(fruit);
}

Using a For Loop

This method gives you more control over indexes:

for (int i = 0; i < fruits.size(); i++) {
System.out.println(fruits.get(i));
}

3. Working with Integer LinkedList

You can also create a LinkedList of numbers and perform mathematical operations.

import java.util.LinkedList;

public class IntegerLinkedListExample {
public static void main(String[] args) {
// Create a LinkedList of Integers
LinkedList<Integer> marks = new LinkedList<>();

// Add marks to the list
marks.add(85);
marks.add(90);
marks.add(75);
marks.add(80);

// Display all marks
System.out.println("Marks List: " + marks);

// Calculate the average mark
int total = 0;
for (int mark : marks) {
total += mark;
}

double average = (double) total / marks.size();
System.out.println("Average Marks: " + average);
}
}

Output:

Marks List: [85, 90, 75, 80]
Average Marks: 82.5

4. Peek and Poll Methods

Java provides two very useful methods in LinkedList, such as peek() and poll(), that we can use when we want to access elements like a queue (FIFO – First In, First Out).

  • The peek() method helps us to see the first elements in the list without removing them.
  • poll() also checks the first element, but it removes it from the list after showing it.

Example: Peek and Poll in Action

import java.util.LinkedList;

public class PeekPollExample {
public static void main(String[] args) {
// Create a LinkedList of colors
LinkedList<String> colors = new LinkedList<>();

// Add elements to the list
colors.add("Red");
colors.add("Blue");
colors.add("Green");

// Display the original list
System.out.println("Original Colors: " + colors);

// Peek method - just shows the first element without deleting
System.out.println("Peek (just see first): " + colors.peek());

// Poll method - shows and removes the first element
System.out.println("Poll (remove first): " + colors.poll());

// Display list after using poll
System.out.println("After Poll Operation: " + colors);
}
}

Output:

Original Colors: [Red, Blue, Green]
Peek (just see first): Red
Poll (remove first): Red
After Poll Operation: [Blue, Green]

Also Learn Important Topics of Java

Leave a Comment