public
E element()
Retrieves,
but does not remove, the head (first element) of this list.
import java.util.*; class LinkedListElement{ public static void main(String args[]){ LinkedList<Integer> myList; myList = new LinkedList<Integer> (); /* Add Elements to myList */ myList.add(10); myList.add(20); myList.add(30); myList.add(40); System.out.println("Elements in myList are " + myList); System.out.println("\nHead Of the myList is " + myList.element()); System.out.println("\nHead Of the myList is " + myList.element()); } }
Output
Elements in myList are [10, 20, 30, 40] Head Of the myList is 10 Head Of the myList is 10
1. Throws
NoSuchElementException if this list is empty
import java.util.*; class LinkedListElementNoSuch{ public static void main(String args[]){ LinkedList<Integer> myList; myList = new LinkedList<Integer> (); System.out.println("Elements in myList are " + myList); System.out.println("\nHead Of the myList is " + myList.element()); } }
Output
Elements in myList are [] Exception in thread "main" java.util.NoSuchElementException at java.util.LinkedList.getFirst(LinkedList.java:242) at java.util.LinkedList.element(LinkedList.java:661) at LinkedListElementNoSuch.main(LinkedListElementNoSuch.java:10)
No comments:
Post a Comment