How do I add item at the beginning or the end of LinkedList?

To add an item before the first item in the linked list we use the LinkedList.addFisrt() method and to add an items after the last item in the linked list we use the LinkedList.addLast() method.

package org.kodejava.example.util;

import java.util.LinkedList;

public class LinkedListAddItems {
    public static void main(String[] args) {
        LinkedList<String> grades = new LinkedList<>();
        grades.add("B");
        grades.add("C");
        grades.add("D");
        grades.add("E");

        System.out.println("Original values are:");
        System.out.println("====================");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }

        grades.addFirst("A");
        grades.addLast("F");

        System.out.println("New values are:");
        System.out.println("====================");
        for (String grade : grades) {
            System.out.println("Grade = " + grade);
        }
    }
}

The result of the program are the following:

Original values are:
====================
Grade = B
Grade = C
Grade = D
Grade = E
New values are:
====================
Grade = A
Grade = B
Grade = C
Grade = D
Grade = E
Grade = F

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.