Friday, December 27, 2024
Google search engine
HomeLanguagesJavaLinkedList getFirst() Method in Java

LinkedList getFirst() Method in Java

Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The Java.util.LinkedList.getFirst() method is used to fetch or retrieve the first element from a LinkedList or the element present at the head of the List.

Illustration:

Input : 4 --> 1 --> 5 --> 6 --> 1 --> 3
Output: 4

As we all know that getFirst() is one of the methods been there up present inside LinkedList class. It retrieves the first element from the object inside which elements of LinkedList are present. As we know LinkedList is a class been present inside java.util package so and if we do operate the following methods the syntax will look like as shown below as follows:

import java.util.LinkedList;
LinkedList ll = new LinkedList<T>();  
ll.getFirst();

In simpler words, if we want to know the first element then do perform the below check as listed below. It will, later on, be illustrated as an example while implementing.

Syntax: 

LinkedList.getFirst();

Return Value: The first element or the element at the head of the list.

Example:

Java




// Java Program to Illustrate getFirst() Method
// of LinkedList class
 
// Importing required classes
import java.io.*;
import java.util.LinkedList;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Creating an empty LinkedList by creating its
        // object Declaring object of type strings
        LinkedList<String> list = new LinkedList<String>();
 
        // Adding custom input elements to the List
        // Using add() method
        list.add("Geeks");
        list.add("for");
        list.add("Geeks");
        list.add("10");
        list.add("20");
 
        // Displaying the list(all elements inside object)
        System.out.println("LinkedList:" + list);
 
        // Fetching first element from the list
        // using getFirst() method
        System.out.println("The first element is: "
                           + list.getFirst());
    }
}


Output: 

LinkedList:[Geeks, for, Geeks, 10, 20]
The first element is: Geeks

 

RELATED ARTICLES

Most Popular

Recent Comments