Skip to content

Java LinkedList Get First and Last Elements Example

This example shows how to get the first element and last element of the LinkedList in Java. This example also shows how to get the first and last element using the getFirst and getLast methods.

How to get the first and last elements of the LinkedList in Java?

1. Using the index

The LinkedList is an index based linked list implementation of the List interface. Since it is an index-based collection, its elements can be accessed using the index.

The List index starts from 0 and ends at the list size-1 index. In other words, the first element of the LinkedList is located at index 0 and the last element of the LinkedList is located at the index list size – 1.

The below given example shows how to get the first and last elements from the linked list using the index.

Output

Note:

Always check the linked list size before calling the get method using the index.

The get method of the LinkedList class throws the IndexOutOfBoundsException if the specified index is out of the range of the list. That is if the specified index is less than 0 or greater than or equal to the list size.

2. Using the getFirst and getLast methods

You can also use the getFirst and getLast methods of the LinkedList class to access the first and last elements of the linked list respectively.

Example

Output

The getFirst and getLast methods throw NoSuchElementException exception if the list is empty. That is why it is necessary to check if the linked list is empty before calling these methods.

This example is a part of the LinkedList in Java tutorial.

Please let me know your views in the comments section below.

References:
Java 8 LinkedList

About the author

Leave a Reply

Your email address will not be published.