Easy Tutorial
❮ Java String Copyvalueof Number Floor ❯

Java Example - Getting the First and Last Elements of a LinkedList

Java Examples

The following example demonstrates how to use the linkedlistname.getFirst() and linkedlistname.getLast() methods of the LinkedList class to get the first and last elements of a linked list:

Main.java File

import java.util.LinkedList;

public class Main {
    public static void main(String[] args) {
        LinkedList<String> lList = new LinkedList<String>();
        lList.add("100");
        lList.add("200");
        lList.add("300");
        lList.add("400");
        lList.add("500");
        System.out.println("The first element of the linked list is: " + lList.getFirst());
        System.out.println("The last element of the linked list is: " + lList.getLast());
    }
}

The above code outputs the following result:

The first element of the linked list is: 100
The last element of the linked list is: 500

Java Examples

❮ Java String Copyvalueof Number Floor ❯