Java LinkedList add(), addFirst(), addLast() and addAll() Example

Java LinkedList Examples


In this post, we will learn how to create a LinkedList and adding elements to it using different LinkedList APIs with an example.

Below are LinkedList API's used to add elements to LinkedList:
  • add(String element) - Adding new elements to the end of the LinkedList using add() method.
  • add(int index, String element) - Adding an element at the specified position in the LinkedList.
  • addFirst(String e) - Adding an element at the beginning of the LinkedList.
  • addLast(String e) - Adding an element at the end of the LinkedList.
  • addAll(Collection<? extends String> c) - Adding all the elements from an existing collection to the end of the LinkedList.

Let's demonstrates the usage of above LinkedList API with an example.

Java LinkedList add(), addFirst(), addLast() and addAll() Example

package com.javaguides.collections.linkedlistexamples;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class CreateLinkedListExample {
    public static void main(String[] args) {
        // Creating a LinkedList
        LinkedList < String > linkedList = new LinkedList < > ();

        // Adding new elements to the end of the LinkedList using add() method.
        linkedList.add("A");
        linkedList.add("B");
        linkedList.add("C");

        System.out.println("Initial LinkedList : " + linkedList);

        // Adding an element at the specified position in the LinkedList
        linkedList.add(3, "Lisa");
        System.out.println("After add(3, \"D\") : " + linkedList);

        // Adding an element at the beginning of the LinkedList
        linkedList.addFirst("Steve");
        System.out.println("After addFirst(\"E\") : " + linkedList);

        // Adding an element at the end of the LinkedList (This method is equivalent to the add() method)
        linkedList.addLast("Jennifer");
        System.out.println("After addLast(\"F\") : " + linkedList);

        // Adding all the elements from an existing collection to the end of the LinkedList
        List < String > familyFriends = new ArrayList < > ();
        familyFriends.add("Jesse");
        familyFriends.add("Walt");

        linkedList.addAll(familyFriends);
        System.out.println("After addAll(familyFriends) : " + linkedList);
    }
}

Output

Initial LinkedList : [A, B, C]
After add(3, "D") : [A, B, C, Lisa]
After addFirst("E") : [Steve, A, B, C, Lisa]
After addLast("F") : [Steve, A, B, C, Lisa, Jennifer]
After addAll(familyFriends) : [Steve, A, B, C, Lisa, Jennifer, Jesse, Walt]

Reference



Comments