Wednesday, October 22, 2025
HomeLanguagesJavaLinkedList getLast() Method in Java

LinkedList getLast() Method in Java

Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and. The Java.util.LinkedList.getLast() method is used to fetch or retrieve the last element from a LinkedList or the element present at the tail of the list.

Illustration:

Input : 4 --> 1 --> 5 --> 6 --> 1 --> 3
Output: 3

As we all know that getLast() is one of the methods been there up present inside LinkedList class. It retrieves the last element from the object inside which elements of LinkedList are present. As we know LinkedList is a class been present inside java.util package so and if we do operate the following methods the syntax will look like as shown below as follows:

import java.util.LinkedList;
LinkedList ll = new LinkedList<T>();  
ll.getLast();

In simpler words, if we want to know the last element or the tail of LinkedList then do perform the below check as listed below. It will, later on, be illustrated as an example while implementing.

Syntax: 

LinkedList.getLast();

Return Type: The last element or the element present at the tail of the list.

Example:

Java




// Java Program to Illustrate getLast() method
 
// Importing required classes
import java.io.*;
import java.util.LinkedList;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Creating an empty LinkedList class object
        // Declaring object of string type
        LinkedList<String> list = new LinkedList<String>();
 
        // Adding elements in the list
        // using add() method
        list.add("Geeks");
        list.add("for");
        list.add("Geeks");
        list.add("10");
        list.add("20");
 
        // Displaying all elements of LinkedList
        System.out.println("LinkedList:" + list);
 
        // Now from these elements procuring
        // last element from the list
        // using getLast() method
        System.out.println("The last element is: "
                           + list.getLast());
    }
}


Output: 

LinkedList:[Geeks, for, Geeks, 10, 20]
The last element is: 20

 

Previous article
Next article
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS