Open In App

LinkedList element() method in Java with Examples

Last Updated : 10 Dec, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

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:




// 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);
        }
    }
}


Output:

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

Example 2:




// 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);
        }
    }
}


Output:

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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads