java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.example.util;

import java.util.LinkedList;

public class LinkedListAddItems {
    public static void main(String[] args) {
        LinkedList<String> grades = new LinkedList<String>();
        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