Java Create LinkedList and Adding New Elements to It



Java LinkedList Examples


This Java example shows how to create LinkedList in Java with an example.

Java LinkedList is a doubly-linked list implementation of Java’s List and Deque interfaces. It is part of Java’s collections framework.

Creating a LinkedList and Adding New Elements to It

The following example shows how to create a LinkedList and add new elements to it. Notice the uses of addFirst() and addLast() methods in the example. These methods come from the Deque interface.
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> fruits = new LinkedList<>();
        
     // Adding new elements to the end of the LinkedList using add() method.
     fruits.add("Banana");
     fruits.add("Apple");
     fruits.add("mango");
        
        System.out.println("Initial LinkedList : " + fruits);

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

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

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

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

        fruits.addAll(moreFruits);
        System.out.println("After addAll(moreFruits) : " + fruits);
    }
}
Output:
Initial LinkedList : [Banana, Apple, mango]
After add(2, "D") : [Banana, Apple, Watermelon, mango]
After addFirst("Strawberry") : [Strawberry, Banana, Apple, Watermelon, mango]
After addLast("F") : [Strawberry, Banana, Apple, Watermelon, mango, Orange]
After addAll(moreFruits) : [Strawberry, Banana, Apple, Watermelon, mango, Orange, Grapes, Pyrus]

Comments