LinkedList in Java With Examples How to Use It

In this blog post we will first cover what is a LinkedList in Java, when to use a Java LinkedList and show you how to use a LinkedList by providing several examples.

What is LinkedList in Java?

Java LinkedList is a collection that implements from the List and Deque interfaces. It lets you add various types of objects into it. In addition, it offers several other methods to access and manipulate the objects it holds. You can see the full list of all the available methods in its’ documentation.

In its’ essence Java LinkedList is a doubly-linked list. It means that every object in the list has two references. One points to the previous object and other points to the next object. To access an object in the LinkedList it has to go through all the elements before or after the searched object. Which way to traverse the list depends on if the object is closer to the start(head) or the end(tail) of the list. When in comes to accessing an object it is different from the ArrayList where we can access objects directly by its’ index. Therefore, LinkedList is slower than ArrayList when accessing objects.

To point out, Java LinkedList is not synchronized. In case there are multiple threads reading from/writing to the LinkedList, you might get some unexpected results.

When to use Java LinkedList?

LinkedList in Java could be used when adding to and removing objects from a collection are the main operations you need to do. In that case LinkedList is faster than ArrayList.

But be careful using a LinkedList in Java. Its’ memory usage is different from the ArrayList. This is because LinkedList also needs to store its’ references (to the next and previous objects) in the memory.

Check out also this interesting tweet from Joshua Bloch about LinkedList.

How to use LinkedList in Java?

LinkedList in Java is simple to use. Now, lets take a look at some examples of how to create a LinkedList in Java and show some possible usages of it.

First, lets create an empty list of animals and add some animals into it. Then, we will print out how many animals are in the list. Note, when we create the LinkedList in this example, we are using the List interface.

// Creating an empty list of animals
List<String> animals = new LinkedList<>();

// Lets add some animals to the list
animals.add("dog");
animals.add("rat");

// Display how many animals we have in the list
System.out.println("Number of animals in the list: " + animals.size());

The output is the following:

Number of animals in the list: 2

Now, lets try to retrieve the first animal from the list:

// Get and display the first animal in the list
String firstAnimal = animals.get(0);
System.out.println("First animal in the list: " + firstAnimal);

The output:

First animal in the list: dog

We can also iterate over the list to display all the animals using foreach:

// Display all animals in the list
for (String animal : animals) {
    System.out.println(animal);
}

… or the Java 8 way:

// Display all animals in the list Java 8 way
animals.forEach(animal -> System.out.println(animal));

The output of the both:

dog
rat

Now lets add a cat after a dog by specifying cats’ position index and display all the animals:

// Add cat to index 1 (after the dog)
animals.add(1, "cat");
animals.forEach(animal -> System.out.println(animal));

The output:

dog
cat
rat

Next lets see how to add another list of animals into the already existing list:

// Create new list by populating it with a list of animals
List<String> otherAnimals = new LinkedList<>(
        Arrays.asList("monkey", "sebra")
);

// Add the otherAnimals list to the animals list and display it
animals.addAll(otherAnimals);
animals.forEach(animal -> System.out.println(animal));

The output:

dog
cat
rat
monkey
sebra

We can also remove the cat from the list:

// Check if list contains a cat
System.out.println(
        "(Before remove) List contains a cat: " + animals.contains("cat")
);

animals.remove("cat");

// Check if list contains a cat
System.out.println(
        "(After remove) List contains a cat: " + animals.contains("cat")
);

The output:

(Before remove) List contains a cat: true
(After remove) List contains a cat: false

So far its’ usage has been similar to ArrayList. This is mostly because we used the List interface when we created our LinkedList. Following are same examples when we use the Deque interface instead to create a LinkedList.

First, lets create a LinkedList and add animals to it. Note the offerFirst() and offerLast() methods to do that:

// Creating an empty deque of animals
Deque<String> animals = new LinkedList<>();

// Lets add some animals to the deque
animals.add("dog");
animals.add("rat");
animals.add("cat");

// Add monkey to the first position (before dog)
animals.offerFirst("monkey");
// Add sebra to the last position (after cat)
animals.offerLast("sebra");

// Display all animals in the deque
animals.forEach(animal -> System.out.println(animal));

The output:

monkey
dog
rat
cat
sebra

Next, lets get the first and last animals in the deque. We can use getFirst() and getLast() methods for that:

// Get first animal
String firstAnimal = animals.getFirst();
System.out.println("First animal in the deque: " + firstAnimal);

// Get last animal
String lastAnimal = animals.getLast();
System.out.println("Last animal in the deque: " + lastAnimal);

The output:

First animal in the deque: monkey
Last animal in the deque: sebra

We can also remove the first and last animal from the deque by polling them. Methods used: pollFirst(), pollLast():

// Poll first animal <- removes the first animal from the deque
String firstPolledAnimal = animals.pollFirst();
System.out.println("First animal polled: " + firstPolledAnimal);


// Poll last animal <- removes the last animal from the deque
String lastPolledAnimal = animals.pollLast();
System.out.println("Last animal polled: " + lastPolledAnimal);

The output:

First animal polled: monkey
Last animal polled: sebra

As a final steps lets see what animals we have left in the deque:

// Display all animals in the deque
animals.forEach(animal -> System.out.println(animal));

The output:

dog
rat
cat

Conclusion

LinkedList in Java is a unsynchronized and doubly-linked collection. It lets you add various types of objects into it. Every object in the list has two references: on the previous object and on the next object. Java LinkedList could be used when adding and removing objects from a collection are the main operations you need to do. But keep in mind that it might use more memory than an ArrayList.

Read also my blog post about ArrayList.

Be the first to reply

Leave a Reply

Your email address will not be published. Required fields are marked *