Linked List in Java | Explained with Coding Example

Linked List in Java | Explained with Coding Example

LinkedList Introduction

LinkedList is one of the most important data structures that is used to store data in computer memory. It is a non-continuous and linear data structure that is a perfect fit for optimum utilization of memory.

It does not store elements continuously but rather stores scattered to fill the unused memory gaps.

In Java, you can implement LinkedList by using the LinkedList class that is available in java.util the package and is a part of the Java collection framework.

In this article, we are going to explore the LinkedList class and its utility methods.

Array and LinkedList both are used to store element/data but LinkedList provides several benefits over the array that are listed below.  

Advantages of LinkedList Over Array

LinkedList has some advantages over an array which make it preferable.

  • Dynamic Memory Allocation: LinkedList is dynamic. It means that the memory of LinkedList is allocated at runtime. We do not need to specify the size of LinkedList while creating it. It automatically increases when we add an element to it and it automatically decreases when we remove any element from it. 

In the case of an array, we cannot add more elements than the size specified initially.

  • No Memory Wastage: Only the required memory is allocated in the case of LinkedList whereas in case of an array, we first need to specify the size, which may or may not be completely filled.
  • Data Insertion and Deletion is easy: In an array, if we want to delete the element at the 2nd position, the element will be removed then all the following elements will be shifted forward by one position. This is a very time-consuming process. But in the case of LinkedList, only the address is changed which makes it fast and easy to implement.

Many students get confused LinkedList with the ArrayList in Java. These are the two different entities.

How LinkedList Works

In LinkedList, the elements are stored in a non-continuous manner. Each element is called a node. Each node has 2 parts:

  • Data Part: This stores the actual value or data to be stored.
  • Address/Link Part: This stores the address of the next node also known as the pointer.

Linked list example:

Implement Linked List in C

Java LinkedList class implements the concept of doubly linked list data structure. So, the address part contains the pointer to the next node as well as the previous node.

Now, let’s start by creating a LinkedList and then perform the basic operations.

Creating LinkedList in Java

To create LinkedList, we must create an object of the LinkedList class by specifying the type of data that this list going to store.

See, here, we created a linked list that can store string elements.

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

Initially, this list is empty and for adding elements this class provides built-in methods. So, let’s add some elements to it and display the result to the console.

Adding Elements to LinkedList

The add() method is used to add elements to LinkedList. This is an instance method so we just used the object of the class to call this method. This method takes a single argument.

import java.util.*;
public class Main
{
	public static void main(String[] args) {
		LinkedList<String> colors=new LinkedList<>();
		colors.add("Pink");
		colors.add("Yellow");
		
		System.out.println(colors);
	}
}

Output:

[Pink, Yellow]

This class provides one more add() method that takes two arguments. The first is the index, and the second is an element. This method adds element to the specified index in the linked list. 

import java.util.*;
public class Main
{
	public static void main(String[] args) {
		LinkedList<String> colors=new LinkedList<>();
		colors.add("Pink");
		colors.add("Yellow");
		colors.add(1,"Blue");
		System.out.println(colors);
	}
}

Output:

[Pink, Blue, Yellow]

Update element in the linked list.

If after adding values to LinkedList, we wish to change the value. We can use the set() method.

This method takes two parameters. The first parameter is the index value of the element that we wish to change and the second parameter is the updated value.

import java.util.*;
public class Main
{
	public static void main(String[] args) {
		LinkedList<String> colors=new LinkedList<>() ;
		colors.add("Pink") ;
		colors.add("Yellow" ) ;
		colors.add(1,"Blue") ;
		System.out.println(colors) ;
		
		colors.set(1,"Red") ;
		System.out.println("After changing values") ;
		System.out.println(colors) ;
	}
}

Output:

[Pink, Blue, Yellow]
After changing values
[Pink, Red, Yellow]

Remove elements from the Linked List

In order to remove the elements from LinkedList, we can use the remove() method. This method has two overloaded versions to remove elements:

  1. remove(Object): It removes the object from the LinkedList. If the object is present at multiple positions, it is removed only from the first occurrence.
  2. remove(int index): it removes the element from the mentioned index position.
mport java.util.*;
public class Main
{
public static void main(String[] args) {
		LinkedList<String> colors=new LinkedList<>();
		colors.add("Pink") ;
		colors.add("Yellow") ;
		colors.add(1,"Blue") ;
		colors.add("Blue") ;
		colors.add("Green") ;
		System.out.println(colors) ;	
	    	
colors.remove("Blue") ; // removing element
	    	colors.remove(3) ; removing element from the index
		
System.out.println("After removing values") ;
		System.out.println(colors) ;
	}
}

Output:

[Pink, Blue, Yellow, Blue, Green]
After removing values
[Pink, Yellow, Blue]

Access Elements of LinkedList

To fetch elements from the LinkedList, we can use the built-in get() method. Here, we are accessing elements of the 2nd index.

import java.util.*;
public class Main
{
	public static void main(String[] args) {
		LinkedList<String> colors=new LinkedList<>();
		colors.add("Pink") ;
		colors.add("Yellow") ;
		colors.add(1,"Blue") ;
		colors.add("Blue") ;
		colors.add("Green") ;
		System.out.println(colors) ;
		
	   	System.out.println( "Element at 2nd index is " + colors.get(2) ) ;
	}
}

Output:

[Pink, Blue, Yellow, Blue, Green]
Element at 2nd index is Yellow.

Iterating Linked List Elements

We can iterate or traverse through all the elements of LinkedList by using the for-each loop. It is a simple and concise way to fetch all the elements sequentially.

import java.util.*;
public class Main
{
	public static void main(String[] args) {
		LinkedList<String> colors = new LinkedList<>();
		colors.add("Pink") ;
		colors.add("Yellow") ;
		colors.add(1,"Blue") ;
		colors.add("Blue") ;
		colors.add("Green") ;
		System.out.println( colors ) ;
		
	   for(String color: colors ) {
            		System.out.print( color )  ;
            		System.out.print(", ") ;
        	   }
	}
}

Output:

[Pink, Blue, Yellow, Blue, Green]
Pink, Blue, Yellow, Blue, Green,

We can also use a simple for loop to iterate Linked List but in this case, we will have to use the get() method to get the elements by passing the index value.

mport java.util.*;
public class Main
{
	public static void main(String[] args) {
		LinkedList<String> colors=new LinkedList<>();
		colors.add("Pink") ;
		colors.add("Yellow") ;
		colors.add(1,"Blue") ;
		colors.add("Blue") ;
		colors.add("Green") ;
		System.out.println(colors) ;
		
	  for (int i = 0 ; i < colors.size() ; i++ ) {
            System.out.print( colors.get(i) + " " )  ; 
        }

	}
}

Output:

[Pink, Blue, Yellow, Blue, Green]
Pink Blue Yellow Blue Green

Useful Methods of the LinkedList Class

  • contains():
    It checks whether the element is present in Linked List or not
  • indexOf():
    It returns the index of elements. In the case of multiple occurrences, the index value of the first occurrence is returned.
  • lastIndexOf():
    It returns the index value of the last occurrence of the element
  • clear():
    It removes all elements of LinkedList.
  • iterator():
    It returns an iterator to iterate the Linked List.
  • toArray():
    It returns an array containing all the values of LinkedList in an ordered manner.
  • toString():
    It returns a string containing all the values of LinkedList in an ordered manner. The values are separated by a comma and the string is enclosed in a square bracket.

Preparing for a Job interview?

If you are preparing for a job interview, this is a very important topic you should prepare. There are a lot of questions related to the linked list usually asked in the interview. One of the common questions is to reverse the linked list in Java.

If you have any doubt, you can ask your question below. I will try my best to keep it simple and easy for you.

Leave a Reply

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