Press "Enter" to skip to content

LinkedList getLast() method with example in java

The getLast() method of LinkedList returns the last element of this linked list. It throws NoSuchElementException if this linked list is empty.

Syntax

Object getLast()

Parameters

it doesn't take any parameter

Return Value

It returns the first element in this linked-list

Exception

throws NoSuchElementException if this  linked-list is empty

Program 1

import java.util.LinkedList;

public class LinkedListGetLastExample {

	public static void main(String[] args) {

		LinkedList<Integer> oddNumbers = new LinkedList<>();
		oddNumbers.add(5);
		oddNumbers.add(7);
		oddNumbers.add(9);
		oddNumbers.add(11);

		System.out.println("Linked List elements: " + oddNumbers);
		System.out.println("Element at index 1 in this linked-list: " + oddNumbers.getLast());

	}
}

Output

Linked List elements: [5, 7, 9, 11]
Element at index 1 in this linked-list: 11

Program 2

import java.util.LinkedList;

public class LinkedListGetLastExample {

	public static void main(String[] args) {

		LinkedList<Integer> oddNumbers = new LinkedList<>();
		oddNumbers.add(5);
		oddNumbers.add(7);
		oddNumbers.add(9);
		oddNumbers.add(11);

		System.out.println("Linked List elements: " + oddNumbers);
		oddNumbers.clear();
		System.out.println("Linked List elements after clear() call: " + oddNumbers);
		System.out.println(oddNumbers.getLast());

	}
}

Output

Linked List elements: [5, 7, 9, 11]
Linked List elements after clear() call: []
Exception in thread "main" java.util.NoSuchElementException
	at java.util.LinkedList.getLast(LinkedList.java:257)
	at LinkedListGetLastExample.main(LinkedListGetLastExample.java:18)

Be First to Comment

Leave a Reply

Your email address will not be published.