What is the LinkedList.getFirst method in Java?

A linked list is a collection of linear data elements. Each element, or node, has two parts: the data and the reference. The data part has the value and the reference part has the address link to the next element. The elements are not indexed, so random access like in arrays is not possible. Instead, we traverse from the beginning of the list and access the elements.

In Java, the LinkedList is the doubly-linked listEach node contains three fields: two link fields (one for the previous element and another for the next element) and one data field. implementation of the List and Dequeue interfaces. The LinkedList class is present in the java.util package.

What is the getFirst method of the LinkedList class?

The getFirst method can be used to get the first element of the LinkedList.

Syntax

public E getFirst();
  • This method doesn’t take any argument.

  • This method returns the first element of the list.

  • If the list is empty, then the NoSuchElementException exception is thrown.

Code

The code below demonstrates how to use the getFirst method:

import java.util.LinkedList;
class LinkedListGetFirst {
public static void main( String args[] ) {
LinkedList<String> list = new LinkedList<>();
list.add("1");
list.add("2");
list.add("3");
System.out.println("The list is " + list);
System.out.println("The first element of the list is " + list.getFirst());
}
}

Explanation

In the code above:

  • In line number 1, we imported the LinkedList class.
import java.util.LinkedList;
  • In line number 4, we created LinkedList objects with the name list.
LinkedList<String> list = new LinkedList<>();
  • From line numbers 5 to 7, we used the add method of the list object to add three elements ("1","2","3") to the list.
list.add("1");
list.add("2");
list.add("3");
  • In line number 10, we used the getFirst method of the list object to get the first element of the list.
list.getFirst(); // "1"

Free Resources