Java - LinkedList Methods Part 1: Adding Elements

Adding elements to a LinkedList can be done in multiple ways, depending on the use case. Common methods include add(), addFirst(), and addLast().

Examples and Explanation

Using add()

import java.util.LinkedList;

public class LinkedListAdd {

    public static void main(String[] args) {

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

        list.add("Apple");

        list.add("Banana");

        System.out.println(list); // Output: [Apple, Banana]

    }

}

Explanation: The add() method appends elements to the end of the LinkedList.

Using addFirst()

list.addFirst("Cherry");

System.out.println(list); // Output: [Cherry, Apple, Banana]

Explanation: This method adds an element to the beginning of the list, making it efficient for queue-like operations.

Using addLast()

list.addLast("Date");

System.out.println(list); // Output: [Cherry, Apple, Banana, Date]

Explanation: Similar to add(), but explicitly adds to the end of the list, useful for clarity in double-ended queue implementations.

Adding at a Specific Index

list.add(1, "Elderberry");

System.out.println(list); // Output: [Cherry, Elderberry, Apple, Banana, Date]

Explanation: This allows insertion at a specific position, shifting subsequent elements.

Adding All Elements from Another Collection

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

anotherList.add("Fig");

anotherList.add("Grape");

list.addAll(anotherList);

System.out.println(list); // Output: [Cherry, Elderberry, Apple, Banana, Date, Fig, Grape]

Explanation: Adds all elements from another collection to the current list.