Java/J2EE and SOA (305 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (45 Blogs)
  • Comprehensive Java Course (2 Blogs)
  • Java/J2EE and SOA (304 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

Linked List in Java: How to Implement a Linked List in Java?

Published on Jun 27,2019 1.2K Views
4 / 19 Blog from Java Collections

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

After arrays, the second most popular data structure is Linked List. A linked list is a linear data structure, made of a chain of nodes in which each node contains a value and a pointer to the next node in the chain. In this article, let’s see how to use Java’s built-in LinkedList class to implement a linked list in Java.

Listed below are the topics covered in this article:

What is a Linked List?

A linked list is a linear data structure with the collection of multiple nodes, where each element stores its own data and a pointer to the location of the next element. The last link in a linked list points to null, indicating the end of the chain. An element in a linked list is called a node. The first node is called the head. The last node is called the tail.

Here’s a simple example: Imagine a linked list like a chain of paperclips that are linked together. You can easily add another paperclip to the top or bottom. It’s even quick to insert one in the middle. All you have to do is to just disconnect the chain at the middle, add the new paperclip, then reconnect the other half. A linked list is similar.

Types of Linked List

Singly Linked List (Uni-Directional)

Doubly Linked List (Bi-Directional)

Circular Linked List

Now, let’s check out how to implement the linked list concept in Java.

Linked List in Java

Java, as a programming language, focuses on code reusability through concepts like classes and objects. A class, in simple terms, is a blueprint or template for an object. While you can build your own custom classes for a linked list implementation, Java does offer a convenient built-in LinkedList class to implement a linked list in Java.

LinkedList Class in Java

In Java, LinkedList class is a doubly-linked list implementation of List and Deque interfaces. It also implements all optional list operations and permits all elements (including null).

LinkedList Class Features

Below you can find the most important properties of the class LinkedList:

  • Implements Queue and Deque interfaces. Therefore, It can also be used as a Queue, Deque or Stack
  • It can contain all the elements, including duplicates and null
  • LinkedList maintains insertion order of the elements
  • Java LinkedList Class is not synchronized, that means in a multi-threaded environment you must synchronize concurrent modifications to the linked list externally
  • We can use Collections.synchronizedList(new LinkedList()) to get synchronized linked list
  • LinkedList Class doesn’t implement RandomAccess interface, so, we can access elements in sequential order only
  • We can use ListIterator to iterate elements of the list

LinkedList Class Declaration

LinkedList is a generic class that has this declaration:

public class LinkedList<E>;
extends AbstractSequentialList<E>;
implements List<E>, Deque<E>, Cloneable, Serializable

Here, E specifies the type of objects that the list holds.

Constructors of LinkedList Class 

LinkedList has the two constructors shown here:

  1. LinkedList( ) – Builds an empty linked list
  2. LinkedList(Collection c)Builds a linked list that is initialized with the elements of the collection c

How to Implement the LinkedList Class?

With the help of multiple example Java programs, let’s try to understand how to implement LinkedList Class in Java. I have used a lot of methods in these example programs.

Example1: Creating a LinkedList and demonstrating the usage of basic methods in the LinkedList class

The following example shows:

  1. Creating a linked list using the LinkedList class
  2. Adding elements to the list in multiple ways
  3. Accessing elements of linked list using get() and set()
  4. How to remove the elements of the linked list
package MyPackage;

import java.util.LinkedList;
import java.util.ListIterator;

public class linkedlist {
    public static void main(String args[]) {

      /* Linked List Declaration */
     LinkedList<String> l_list = new LinkedList<String>();
      /*add(String Item) is used for adding 
       * the Items to the linked list*/
      l_list.add("Java");
      l_list.add("Python");
      l_list.add("Scala");
      l_list.add("Swift");
      System.out.println("Linked List Content: " +l_list);
      
      /*Add Items at specified position*/
      l_list.add(2, "JavaScript");
      l_list.add(3, "Kotlin");
      System.out.println("l_list Content after editing: " +l_list);

      /*Add First and Last Item*/
      l_list.addFirst("First Course");
      l_list.addLast("Last Course");
      System.out.println("l_list Content after addition: " +l_list);
      
      /*Get and set Items in the list*/
      Object firstvar = l_list.get(0);
      System.out.println("First Item: " +firstvar);
      l_list.set(0, "Java9");
      System.out.println("l_list Content after updating first Item: " +l_list);
      
      /* Remove from a position*/
      l_list.remove(1);
      l_list.remove(2);
      System.out.println("LinkedList after deletion of Item in 2nd and 3rd position " +l_list);

      /*Remove first and last Item*/
      l_list.removeFirst();
      l_list.removeLast();
      System.out.println("Final Content after removing first and last Item: "+l_list);
      
      /*Iterating the linked list*/
      ListIterator<String> itrator = l_list.listIterator();
      System.out.println("List displayed using iterator:");
      while (itrator.hasNext()) {
          System.out.println(itrator.next());

    }
}
}
    

Output:

Linked List Content = { Java, Python, Scala, Swift}
Content after editing =  { Java, Python, JavaScript, Kotlin, Scala, Swift }
Content after addition = { First Course, Java, Python, JavaScript, Kotlin, Scala, Swift, Last Course }
First Item = { First Course }
Content after updating first item = { Java9, Java, Python, JavaScript, Kotlin, Scala, Swift, Last Course }
Content after deletion of item in 2nd and 3rd position = { Java9, Python, Kotlin, Scala, Swift, Last Course }
Final Content after removing first and last Item = { Python, Kotlin, Scala, Swift }
List displayed using iterator = 
Python
Kotlin
Scala
Swift

There’s a variety of built-in methods that you can use when working with your linked list. As you can see, the above program demonstrates the use of a lot of basic methods whose functionality I have specified below:

  • add(E e) – This method adds elements to the linked list one after the other
  • add​(int index, E element)  – This method adds the specified element at the specified position in this list
  • addFirst(E e) – This method adds the specified element at the beginning of this list
  • addLast​(E e) –  This method adds the specified element to the end of this list
  • get​(int index): This method returns the element at the specified position in this list
  • set​(int index, E element): This method replaces the element at the specified position in this list with the specified element
  • remove​(int index): This method removes the element at the specified position in this list
  • removeFirst​(): This method removes and returns the first element from this list
  • removeLast​(): This method removes and returns the last element from this list

Apart from these, there are a lot of other methods that you can use when working with the LinkedList class. Let’s explore a few more.

Example2: A Java program to convert linked list to an array

The following example shows how to find the size of the linked list and convert the linked list to an array.

package MyPackage;

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

public class linkedlisttoarray 
{
	public static void main(String[] args) 
	{		
		List<String> courseList = new LinkedList<>();
		courseList.add("Java");
		courseList.add("Python");
		courseList.add("DevOps");
		courseList.add("Hadoop");
		courseList.add("AWS");
		int size = courseList.size(); 
        System.out.println("Size of linked list = " + size);
		String[] numbers = new String[size];
		
		numbers = courseList.toArray(numbers);
		System.out.println("Elements of array are:");
		System.out.println(Arrays.toString(numbers));

	}
}

Output:

Size of linked list = 5
Elements of array are:
[Java, Python, DevOps, Hadoop, AWS]

In the above example, I have used two important methods of LinkedList class of Java. Those methods and their functionalities are listed below:

  • size​(): This method returns the number of elements in this list.
  • toArray​(): This method returns an array containing all of the elements in this list in proper sequence

Example2: A Java program to convert array to a linked list

The following example shows how to convert an array to a linked list

package MyPackage;

import java.util.LinkedList;
import java.util.List;

public class ArrayToLinkedList {

		public static void main(String[] args) 
		{
			String[] courses = {"Java","PHP","Hadoop","DevOps","Python"};
			List<String> coursesList = new LinkedList<>();
			for(String s : courses){
				coursesList.add(s);
			}
			System.out.println("The array of popular courses is: " + coursesList);
		}

}

Output:

The array of popular courses is: [Java, PHP, Hadoop, DevOps, Python]

Well, in the above example, I used for loop and add() method to convert an array to a linked list. This way we can use a lot of methods when working with a linked list using LinkedList class in Java. To know about other methods that you can use, refer to the official documentation by Oracle on LinkedList Class in Java.

ArrayList vs LinkedList

Often, programmers confuse ArrayList properties with LinkedList properties. Though both of them implement the List interface, they have different semantics, which will definitely affect the decision of which one to use. 

Listed below are some differences between ArrayList and LinkedList:

FeatureArrayList ClassLinkedList Class

Based On

Based on doubly linked list implementation

Based on the concept of dynamically resizable array

Operations

Insertion, addition and removal operations of an item are faster 

Comparatively, operations are slow here

No of Methods

Offers more methods

Offers fewer methods

Memory

Consumes more memory than an ArrayList

Consumes less memory

  • ArrayList is based on the concept of a dynamic resizable array, while LinkedList is based on doubly linked list implementation
  • The insertion, addition and removal operations of an item are faster in a LinkedList because we don’t need to resize as we do in ArrayList
  • LinkedList class offers comparatively more methods than ArrayList class
  • LinkedList consumes more memory than an ArrayList because every node in a LinkedList stores two references, whereas ArrayList holds only data and its index

That’s all folks! This brings us to the end of this article on the linked list in Java. I hope the Java LinkedList class examples that we discussed here will help you in getting started with LinkedList programming in Java.

Make sure you practice as much as possible and revert your experience.

If you found this article on “Linked List in Java”, check out the Java Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. 

Comments
0 Comments

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.