0
0
JavaHow-ToBeginner · 3 min read

How to Create LinkedList in Java: Simple Guide with Example

In Java, you can create a linked list by using the LinkedList class from the java.util package. You create an instance with LinkedList<Type> list = new LinkedList<>(); and then add elements using methods like add().
📐

Syntax

The basic syntax to create a linked list in Java uses the LinkedList class from java.util. You specify the type of elements inside angle brackets <>. For example, LinkedList<String> creates a list of strings.

  • LinkedList<Type> list = new LinkedList<>(); - creates an empty linked list of the specified type.
  • add(element) - adds an element to the end of the list.
  • get(index) - retrieves the element at the given position.
java
import java.util.LinkedList;

LinkedList<Type> list = new LinkedList<>();
list.add(element);
💻

Example

This example shows how to create a linked list of strings, add some names, and print them one by one.

java
import java.util.LinkedList;

public class LinkedListExample {
    public static void main(String[] args) {
        LinkedList<String> names = new LinkedList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        for (String name : names) {
            System.out.println(name);
        }
    }
}
Output
Alice Bob Charlie
⚠️

Common Pitfalls

Some common mistakes when creating or using linked lists in Java include:

  • Forgetting to import java.util.LinkedList, which causes a compilation error.
  • Using raw types like LinkedList list = new LinkedList(); instead of specifying the type, which can lead to unsafe code.
  • Accessing elements by index without checking if the index is valid, causing IndexOutOfBoundsException.
  • Confusing LinkedList with ArrayList in terms of performance characteristics.
java
/* Wrong way: Missing import and raw type usage */
// LinkedList list = new LinkedList(); // Unsafe, no type specified

/* Right way: */
import java.util.LinkedList;
LinkedList<String> list = new LinkedList<>();
list.add("Example");
📊

Quick Reference

Here is a quick summary of useful LinkedList methods:

MethodDescription
add(element)Adds element to the end of the list
addFirst(element)Adds element at the start of the list
addLast(element)Adds element at the end of the list
get(index)Returns element at specified index
remove()Removes and returns the first element
remove(index)Removes element at specified index
size()Returns number of elements in the list
clear()Removes all elements from the list

Key Takeaways

Use java.util.LinkedList with a specified type to create a linked list in Java.
Always import java.util.LinkedList before using it to avoid errors.
Add elements using add() and access them safely with get() or iteration.
Avoid raw types to keep your code type-safe and clear.
Check list size before accessing elements by index to prevent exceptions.