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:
// 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
filter_none
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); } } } |
chevron_right
filter_none
Output:
LinkedList : [A, B, C] Head of list : A
Recommended Posts:
- LinkedList descendingIterator() method in Java with Examples
- Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
- ArrayList and LinkedList remove() methods in Java with Examples
- LinkedList set() Method in Java
- LinkedList add() Method in Java
- LinkedList pop() Method in Java
- LinkedList get() Method in Java
- LinkedList contains() Method in Java
- AbstractQueue element() method in Java with examples
- LinkedList removeFirst() Method in Java
- LinkedList push() Method in Java
- LinkedList removeLastOccurrence() method in Java with Example
- LinkedList listIterator() Method in Java
- LinkedList toArray() method in Java with Example
- LinkedList clone() Method in Java
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.



