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

Swatee Chand
Edureka
Published in
8 min readJun 27, 2019

After the next node in the chain. In this article, let’s see how to use Java’s built-in 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 LinkedList class to implement a linked list in Java.

Listed below are the topics covered in this article:

1)What is a Linked List?

2)Linked List in Java

  • Java LinkedList Class
  • LinkedList Class Features
  • LinkedList Class Declaration
  • Constructors of LinkedList

3)How to implement LinkedList Class?

  • Java Program Demonstrating Basic Methods of LinkedList Class
  • Program to Converting Linked List to Array
  • Program to Converting Array to Linked List

4)ArrayList vs LinkedList

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, the 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 the 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 =PythonKotlinScalaSwift

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 = 5Elements of array are:[Java, Python, DevOps, Hadoop, AWS]

In the above example, I have used two important methods of the 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:

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.
If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Java.

1. Object Oriented Programming

2. Inheritance in Java

3. Polymorphism in Java

4. Abstraction in Java

5. Java String

6. Java Array

7. Java Collections

8. Java Threads

9. Introduction to Java Servlets

10. Servlet and JSP Tutorial

11. Exception Handling in Java

12. Java Tutorial

13. Java Interview Questions

14. Java Programs

15. Kotlin vs Java

16. Dependency Injection Using Spring Boot

17. Comparable in Java

18. Top 10 Java frameworks

19. Java Reflection API

20. Top 30 Patterns in Java

21. Core Java Cheat Sheet

22. Socket Programming In Java

23. Java OOP Cheat Sheet

24. Annotations in Java

25. Library Management System Project in Java

26. Trees in Java

27. Machine Learning in Java

28. Top Data Structures & Algorithms in Java

29. Java Developer Skills

30. Top 55 Servlet Interview Questions

31. Top Java Projects

32. Java Strings Cheat Sheet

33. Nested Class in Java

34. Java Collections Interview Questions and Answers

35. How to Handle Deadlock in Java?

36. Top 50 Java Collections Interview Questions You Need to Know

37. What is the concept of String Pool in Java?

38. What is the difference between C, C++, and Java?

39. Palindrome in Java- How to check a number or string?

40. Top MVC Interview Questions and Answers You Need to Know

41. Top 10 Applications of Java Programming Language

42. Deadlock in Java

43. Square and Square Root in Java

44. Typecasting in Java

45. Operators in Java and its Types

46. Destructor in Java

47. Binary Search in Java

48. MVC Architecture in Java

49. Hibernate Interview Questions And Answers

Originally published at https://www.edureka.co on June 27, 2019.

--

--