Java Program to Add elements to a LinkedList

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Add Elements Using add()

import java.util.LinkedList;

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

    // create a linkedlist
    LinkedList<String> languages = new LinkedList<>();

    // Add elements to LinkedList
    languages.add("Java");
    languages.add("Python");
    languages.add("JavaScript");
    System.out.println("LinkedList: " + languages);
  }
}

Output

LinkedList: [Java, Python, JavaScript]

Here, the add() method inserts an element at the end of a linkedlist. However, we can also insert elements at the specified position using the add() method.

Example 2: Add element at the specified position

import java.util.LinkedList;

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

    // create a linkedlist
    LinkedList<String> languages = new LinkedList<>();

    // add elements to LinkedList
    languages.add("Swift");
    languages.add("Python");
    System.out.println("LinkedList: " + languages);

    // add element at the specified position
    languages.add(0, "Java");
    System.out.println("Updated LinkedList: " + languages);
  }
}

Output

LinkedList: [Swift, Python]
Updated LinkedList: [Java, Swift, Python]

In the example, notice the line,

languages.add(0, "Java");

Here, 0 is an optional parameter that specifies the index number where the new element is to be added.


Example 3: All all elements from other collection to LinkedList

To add all the elements of a collection to another linked list, we use the addAll() method.

import java.util.LinkedList;

class Main {
  public static void main(String[] args) {
    LinkedList<String> mammals = new LinkedList<>();

    mammals.add("Dog");
    mammals.add("Cat");
    mammals.add("Horse");
    System.out.println("Mammals: " + mammals);

    LinkedList<String> animals = new LinkedList<>();
    animals.add("Crocodile");

    // Add all elements of mammals in animals
    animals.addAll(mammals);
    System.out.println("Animals: " + animals);
  }
}

Output

Mammals: [Dog, Cat, Horse]
Animals: [Crocodile, Dog, Cat, Horse]

Example 4: Using listIterator() method

We can also use the listsIterator() method to add elements to the linked list. To use it, we must import java.util.ListIterator package.

import java.util.ArrayList;
import java.util.ListIterator;

class Main {
  public static void main(String[] args) {
    ArrayList<String> languages = new ArrayList<>();

    // Creating an object of ListIterator
    ListIterator<String> listIterate = languages.listIterator();
    listIterate.add("Java");
    listIterate.add("Python");

    System.out.println("LinkedList: " + languages);
  }
}

Output

LinkedList: [Java, Python]
Did you find this article helpful?