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:
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
LinkedList<Integer> list = new LinkedList<Integer>();
list.add( 10 );
list.add( 20 );
list.add( 30 );
System.out.println( "LinkedList : " + list);
int value = list.element();
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:
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
LinkedList<String> list = new LinkedList<String>();
list.add( "A" );
list.add( "B" );
list.add( "C" );
System.out.println( "LinkedList : " + list);
String value = list.element();
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
Last Updated :
10 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...