The LinkedList.getLast()
method in Java is used to retrieve, but not remove, the last element of a LinkedList
. This guide will cover the method’s usage, explain how it works, and provide examples to demonstrate its functionality.
Table of Contents
- Introduction
getLast
Method Syntax- Examples
- Retrieving the Last Element
- Handling NoSuchElementException
- Conclusion
Introduction
The LinkedList.getLast()
method is a member of the LinkedList
class in Java. It allows you to access the last element of the LinkedList
without removing it. This method is particularly useful for peek operations in deque-like structures.
getLast Method Syntax
The syntax for the getLast
method is as follows:
public E getLast()
- Returns: The last element in this list.
- Throws:
NoSuchElementException
if the list is empty.
Examples
Retrieving the Last Element
The getLast
method can be used to retrieve the last element of a LinkedList
.
Example
import java.util.LinkedList;
public class GetLastExample {
public static void main(String[] args) {
// Creating a LinkedList of Strings
LinkedList<String> list = new LinkedList<>();
// Adding elements to the LinkedList
list.add("Apple");
list.add("Banana");
list.add("Orange");
// Retrieving the last element using getLast() method
String lastElement = list.getLast();
// Printing the last element
System.out.println("Last element: " + lastElement);
}
}
Output:
Last element: Orange
Handling NoSuchElementException
If the LinkedList
is empty, the getLast
method throws a NoSuchElementException
. It is important to handle this exception to avoid runtime errors.
Example
import java.util.LinkedList;
import java.util.NoSuchElementException;
public class GetLastExample {
public static void main(String[] args) {
// Creating an empty LinkedList of Strings
LinkedList<String> list = new LinkedList<>();
try {
// Attempting to retrieve the last element from an empty list
String lastElement = list.getLast();
System.out.println("Last element: " + lastElement);
} catch (NoSuchElementException e) {
System.out.println("Exception: The list is empty.");
}
}
}
Output:
Exception: The list is empty.
Conclusion
The LinkedList.getLast()
method in Java provides a way to retrieve, but not remove, the last element of a LinkedList
. By understanding how to use this method, you can efficiently access the last element in your Java applications without modifying the list. Handling the potential NoSuchElementException
ensures your code remains robust and error-free when dealing with empty lists.