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.
        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
        System.out.println("After addFirst(\"Strawberry\") : " + fruits);

        // Adding an element at the end of the LinkedList 
        // (This method is equivalent to the add() method)
        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<>();

        System.out.println("After addAll(moreFruits) : " + fruits);
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]

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course