LinkedList in Java

LinkedList is a widely used data structure in the Java programming language. It is a part of the Java Collection Framework and is an implementation of the List interface. It is implemented using a doubly-linked list, which allows for fast and efficient data retrieval, insertion, and deletion. In this blog post, we will discuss what LinkedList is. How it works. And how to use it in Java, including examples of all the available methods.

What is LinkedList in Java?

A LinkedList is an ordered collection of elements that allows for duplicate values. It is implemented using a doubly-linked list, which means that each element is linked to the previous and next elements. This allows for fast and efficient data retrieval, insertion, and deletion, especially at the beginning or end of the list.

Why use LinkedList in Java?

LinkedList is useful in situations where we need to work with a collection of objects and need to maintain the order of the elements. It is particularly useful when we need to perform operations such as adding and removing elements at the beginning or end of the List.

LinkedList also provides a linked list implementation for stack and queue operations which allows for fast insertions and deletions at the beginning and end of the list.

How to use LinkedList in Java?

Using LinkedList in Java is relatively simple. To create a LinkedList, we first need to import the java.util package, which contains the LinkedList class.

Following is an example of creating a LinkedList and adding data to it:

import java.util.LinkedList;

LinkedList<Integer> list = new LinkedList<Integer>();
list.add(1);
list.add(2);
list.add(3);

The output of the above example is given below:

[1, 2, 3]

Once we have created the LinkedList, we can add data to it using the add() method. In the example above, we are adding three elements to the LinkedList.

We can also retrieve data from a LinkedList using the get() method. For example, to retrieve the second element in the LinkedList, we can use the following code:

The output of the above example code is:

2

LinkedList also provides several other useful methods such as addFirst(), addLast(), removeFirst(), removeLast(), and size() to manipulate the elements in the list. These methods’ use case is described in the table below:

MethodDescription
void addFirst(E element);Inserts the specified element at the beginning of this list.
void addLast(E element);Appends the specified element to the end of this list.
E removeFirst();Removes and returns the first element from this list.
E removeLast();Removes and returns the last element from this list.
int size();Returns the number of elements in this list.

Further reading:

Reference: LinkedList

Sharing Is Caring: