1. Introduction
In Java, the LinkedList class provides methods to easily retrieve the first and the last elements of the list. The getFirst() and getLast() methods are commonly used for this purpose. This blog post will guide you on how to use these methods to access the first and last elements of a LinkedList in Java.
2. Program Steps
1. Create and initialize a LinkedList.
2. Use the getFirst() method to retrieve the first element of the LinkedList.
3. Use the getLast() method to retrieve the last element of the LinkedList.
4. Print the retrieved first and last elements.
3. Code Program
import java.util.LinkedList;
public class LinkedListGetFirstLastExample {
public static void main(String[] args) {
// Step 1: Create and initialize a LinkedList
LinkedList<String> fruits = new LinkedList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Step 2: Use the getFirst() method to retrieve the first element
String firstElement = fruits.getFirst();
// Step 3: Use the getLast() method to retrieve the last element
String lastElement = fruits.getLast();
// Step 4: Print the retrieved first and last elements
System.out.println("First Element: " + firstElement);
System.out.println("Last Element: " + lastElement);
}
}
Output:
First Element: Apple Last Element: Cherry
4. Step By Step Explanation
Step 1: We create and initialize a LinkedList named fruits with the elements "Apple", "Banana", and "Cherry".
Step 2: We use the getFirst() method of the LinkedList class to retrieve the first element of the list, which is "Apple", and store it in the variable firstElement.
Step 3: Similarly, we use the getLast() method to retrieve the last element of the list, which is "Cherry", and store it in the variable lastElement.
Step 4: Finally, we print the retrieved first and last elements to the console, which are "Apple" and "Cherry" respectively.
In conclusion, the getFirst() and getLast() methods allow us to easily access the first and last elements of a LinkedList in Java.