How do I add first and last items from LinkedList?

Category: java.util, viewed: 294 time(s).

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<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
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats