LinkedList element() method in Java with Examples

The element() method of java.util.LinkedList class retrieves, but does not remove, the head (first element) of this list.

Syntax:

public E element()

Return Value: This method returns the head of this list.

Below are the examples to illustrate the element() method

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// element() method
// for Integer value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        try {
  
            // creating object of LinkedList<Integer>
            LinkedList<Integer> list = new LinkedList<Integer>();
  
            // add some elements to list
            list.add(10);
            list.add(20);
            list.add(30);
  
            // print the linked list
            System.out.println("LinkedList : " + list);
  
            // getting the head of list
            // using element() method
            int value = list.element();
  
            // print the head of list
            System.out.println("Head of list : " + value);
        }
  
        catch (NullPointerException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}

chevron_right


Output:

LinkedList : [10, 20, 30]
Head of list : 10

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// element() method
// for String value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        try {
  
            // creating object of LinkedList<String>
            LinkedList<String> list = new LinkedList<String>();
  
            // add some elements to list
            list.add("A");
            list.add("B");
            list.add("C");
  
            // print the linked list
            System.out.println("LinkedList : " + list);
  
            // getting the head of list
            // using element() method
            String value = list.element();
  
            // print the head of list
            System.out.println("Head of list : " + value);
        }
  
        catch (NullPointerException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}

chevron_right


Output:

LinkedList : [A, B, C]
Head of list : A


My Personal Notes arrow_drop_up

Image
Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.