Linked List in Java

Linked List

ArrayList and LinkedList are almost the same. They can do the same work, but the implementation is different. You can use LinkedList for data manipulation and ArrayList for sorting and accessing. In searching, LinkedList is slow, and in data manipulation /change, ArrayList is slow. To use Linked List, you must import java.util.LinkedList;.

Info

Note: It is a good habit to use ArrayList to sort and access the data and LinkedList to manipulate it.

Syntax

import java.util.LinkedList; // First Import this

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

Add Items To Linked List

import java.util.Collections;
import java.util.LinkedList;

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

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

        names.add("Tanisha Thapa");
        names.add("Mamita Shrestha");
        names.add("Shradha Shrestha");
        names.add("Anar Singh Basnet");

        // sort names
        Collections.sort(names);

        // to print details
        for(String name: names){
            System.out.println(name);
        }

    }
}
Show Output

Useful LinkedList Methods

Methods Description
names.addFirst(); Add item at index 0.
names.addLast(); Add item to last of list.
names.removeFirst(); Remove item at index 0.
names.removeLast(); Remove item at end of list.
names.getFirst(); Get first item of list.
names.getLast(); Get last item of list.
names.size(); Total number of items.
Info

Common Mistake: Don’t create a class name as LinkedList. It is already defined in Java.