Java LinkedList

A LinkedList in Java is a data structure from the java.util package that provides a doubly-linked list implementation. Unlike arrays or ArrayLists, LinkedLists use nodes to store data and links to the next and previous nodes, offering efficient insertion and deletion at the expense of slower access times.

In this guide by The Coding College, we’ll explore what LinkedLists are, how to use them, and their advantages over other data structures.

What is a LinkedList?

A LinkedList:

  • Is part of the List and Deque interfaces.
  • Supports dynamic memory allocation.
  • Stores elements in nodes connected via pointers.
  • Allows null elements and duplicate entries.
  • Supports insertion and deletion operations efficiently.

Syntax to Create a LinkedList

import java.util.LinkedList;

LinkedList<Type> listName = new LinkedList<Type>();

Example:

LinkedList<String> names = new LinkedList<String>();

Features of LinkedList

  1. Dynamic Sizing: Grows or shrinks dynamically.
  2. Efficient Insertion/Deletion: Operations are faster than in an ArrayList for large datasets.
  3. Implements Queue and Deque: Can be used as a stack, queue, or deque.

How to Use LinkedList

1. Importing LinkedList

import java.util.LinkedList;

2. Creating a LinkedList

LinkedList<String> cities = new LinkedList<String>();

Adding Elements

cities.add("New York");
cities.add("London");
cities.add("Tokyo");
System.out.println(cities);

Output:

[New York, London, Tokyo]

Accessing Elements

System.out.println(cities.get(1)); // Access element at index 1

Output:

London

Modifying Elements

cities.set(0, "Paris");
System.out.println(cities);

Output:

[Paris, London, Tokyo]

Removing Elements

cities.remove(2); // Remove element at index 2
System.out.println(cities);

Output:

[Paris, London]

LinkedList Size

System.out.println("Size: " + cities.size());

Output:

Size: 2

Iterating Through a LinkedList

Using a For Loop

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

Using a For-Each Loop

for (String city : cities) {
    System.out.println(city);
}

Using an Iterator

import java.util.Iterator;

Iterator<String> iterator = cities.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

Common LinkedList Methods

MethodDescription
add(element)Adds an element to the end of the list.
add(index, element)Inserts an element at the specified index.
get(index)Returns the element at the specified index.
set(index, element)Updates the element at the specified index.
remove(index)Removes the element at the specified index.
clear()Removes all elements from the list.
size()Returns the number of elements in the list.
contains(element)Checks if the list contains the specified element.
indexOf(element)Returns the index of the first occurrence of the specified element.
isEmpty()Checks if the list is empty.
addFirst(element)Adds an element to the beginning of the list.
addLast(element)Adds an element to the end of the list.
removeFirst()Removes the first element of the list.
removeLast()Removes the last element of the list.

Example: Real-Life Use Case – Task Management

import java.util.LinkedList;

public class TaskManager {
    public static void main(String[] args) {
        LinkedList<String> tasks = new LinkedList<>();

        // Adding tasks
        tasks.add("Complete project report");
        tasks.add("Attend team meeting");
        tasks.add("Submit assignment");

        // Displaying tasks
        System.out.println("Tasks: " + tasks);

        // Completing the first task
        tasks.removeFirst();
        System.out.println("Remaining Tasks: " + tasks);

        // Adding a high-priority task
        tasks.addFirst("Fix critical bug");
        System.out.println("Updated Tasks: " + tasks);
    }
}

Benefits of LinkedList

  1. Dynamic Size: No need to specify size during initialization.
  2. Efficient Insertions/Deletions: Better performance for adding or removing elements from the middle.
  3. Implements Both List and Queue: Can be used as a stack, queue, or deque.

Limitations of LinkedList

  1. Slower Access Times: Accessing elements by index is slower compared to ArrayLists.
  2. Increased Memory Usage: Each node stores a reference to the next and previous nodes, consuming more memory.

When to Use LinkedList

  • Frequent Insertions/Deletions: Best for applications where insertion and deletion operations are frequent.
  • Dynamic Size: Suitable for scenarios where the number of elements changes frequently.

Conclusion

The LinkedList class in Java is a versatile and efficient data structure for managing dynamic data. With its robust functionality, it’s ideal for applications requiring frequent modifications.

Stay tuned for more Java tutorials at The Coding College and elevate your programming knowledge!

Leave a Comment