Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

LinkedList → Java LinkedList


Java LinkedList

Linked List in Java Collections

The LinkedList class in Java provides a linked list implementation of the List interface. Unlike ArrayList which uses an array, LinkedList stores elements in a chain of separate nodes. Each node contains the element itself and a reference (link) to the next node in the list. Benefits : Fast insertions/removals at any position: Adding or removing elements in the middle of the list only requires modifying the links between nodes, making these operations efficient (average constant time). Dynamic size: The size of the list is not limited by a pre-allocated array. It can grow or shrink as needed. Disadvantages : Slower random access: Retrieving elements by their index (position) requires traversing the linked list from the beginning, making random access slower compared to ArrayList. More memory overhead: Each node in a linked list stores an extra reference to the next node, which can lead to slightly higher memory usage compared to an ArrayList.

Declaring a LinkedList

Declaring a LinkedList involves creating a reference variable of the LinkedList class. This variable will hold the reference to the actual LinkedList object you create.
LinkedList declaration syntaxLinkedList<DataType> listName;
Explanation : LinkedList: This specifies the class you're using to create the list. <DataType>: This is a placeholder for the actual data type the list will store (e.g., String, Integer, etc.). Replace it with the desired data type for your elements. listName: This is the name you choose for your reference variable. It can be any valid identifier.

Initializing a LinkedList

There are two main ways to initialize a LinkedList in Java:

1. Creating an empty LinkedList

Creating empty linkedlistLinkedList<String> fruits = new LinkedList<>();
Explanation : ⮚ You use new LinkedList<>() to create a new, empty LinkedList object. ⮚ The angle brackets <> specify the data type the list will hold (String in this case). ⮚ You assign this object to the reference variable fruits. Now, fruits points to an empty LinkedList.

2. Creating a LinkedList with initial elements (Collection initializer):

Creating linkedlist with elements LinkedList<String> colors = new LinkedList<>() {{ add("Red"); add("Green"); add("Blue"); }};
Explanation : ⮚ You use a collection initializer within the LinkedList constructor. ⮚ This allows you to directly add elements ("Red", "Green", "Blue") during creation. ⮚ The code inside the curly braces {} defines the initial elements to be added.

Example of Combining Declaration and Initialization:

linkedlist simple example in java import java.util.LinkedList; public class Main { public static void main(String[] args) { // Declare and initialize an empty LinkedList of countries LinkedList<String> countries = new LinkedList<>(); // Alternatively, initialize with initial elements LinkedList<Integer> numbers = new LinkedList<>() {{ add(10); add(20); add(30); }}; // Add elements to the empty list (countries) countries.add("India"); countries.add("France"); for(int number:numbers){ System.out.println(number); } for(String name:countries){ System.out.println(name); } } }


10 20 30 India France
Explanation : ⮚ This example demonstrates both ways to initialize a LinkedList: ⮚ An empty LinkedList named countries is declared and then elements are added using add(E element). ⮚ A LinkedList named numbers is declared and initialized with initial elements (10, 20, 30) using a collection initializer.

Common Operations with LinkedList

Adding elements: add(E element): Adds the element to the end of the list. add(int index, E element): Inserts the element at the specified index, modifying the links between nodes. Accessing elements: get(int index): Retrieves the element at the specified index by traversing the list from the beginning. Removing elements: remove(int index): Removes the element at the specified index and updates the links between nodes. remove(Object o): Removes the first occurrence of the specified element from the list. Iterating through elements: You can use a for loop with an iterator or a for-each loop to iterate through elements. Checking size: size(): Returns the number of elements in the list.

Simple example Using LinkedList

Basic linkedlist example in java import java.util.LinkedList; public class Main { public static void main(String[] args) { // Create a LinkedList of countries LinkedList<String> countries = new LinkedList<>(); countries.add("India"); countries.add("France"); // Add to the end // Insert element at a specific position countries.add(1, "China"); // Remove element by index countries.remove(2); // Remove "France" // Iterate through elements using for-each loop for (String country : countries) { System.out.println(country); } } }


India China
Explanation : This example demonstrates basic operations like adding, inserting, removing, iterating, and checking the size of a LinkedList.
here are some examples of using LinkedList in Java with different data types:

1. String LinkedList

String Linkedlist example in java import java.util.LinkedList; public class Main { public static void main(String[] args) { // Create a LinkedList to store Strings LinkedList<String> fruits = new LinkedList<String>(); // Add elements to the list fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); // Print the contents of the list System.out.println(fruits); // Access elements by index String firstFruit = fruits.get(0); System.out.println("First fruit: " + firstFruit); // Remove an element fruits.remove("Banana"); System.out.println(fruits); } }


[Apple, Banana, Orange] First fruit: Apple [Apple, Orange]

2. Integer LinkedList

Integer Linkedlist example in java import java.util.LinkedList; public class Main { public static void main(String[] args) { // Create a LinkedList to store Integers LinkedList<Integer> numbers = new LinkedList<>(); // Add elements to the list numbers.add(10); numbers.add(20); numbers.add(30); // Print the contents of the list System.out.println(numbers); // Access elements by index int secondNumber = numbers.get(1); System.out.println("Second number: " + secondNumber); // Remove an element numbers.remove(Integer.valueOf(20)); // Use Integer.valueOf() for autoboxing System.out.println(numbers); } }


[10, 20, 30] Second number: 20 [10, 30]

3. Custom Object LinkedList

Linkedlist with objects example in java import java.util.*; class Product { String name; double price; public Product(String name, double price) { = name; this.price = price; } } public class Main { public static void main(String[] args) { // Create a LinkedList to store Product objects LinkedList<Product> products = new LinkedList<>(); // Create Product objects and add them to the list Product p1 = new Product("prod1",12.009); products.add(p1); Product p2 = new Product("prod2",32.00); products.add(p2); products.add(new Product("prod3",31.900)); System.out.println(products.get(2).price); for(Product product:products){ System.out.println( + " " + product.price); } } }


31.9 prod1 12.009 prod2 32.0 prod3 31.9
Remember, although LinkedList allows storing different data types, it's generally recommended to use a generic type like <String> or for better type safety and code clarity.