public
E pop()
Removes
and returns the first element of this list. This method is equivalent
to removeFirst().
import java.util.*; class LinkedListPop{ public static void main(String args[]){ LinkedList<Integer> myList; myList = new LinkedList<> (); /* Add Elements to myList */ myList.add(10); myList.add(20); myList.add(30); myList.add(40); System.out.println("Elements in myList are"); System.out.println(myList); System.out.print("Pop removes element "); System.out.println(myList.pop()); System.out.println("Elements in myList are"); System.out.println(myList); } }
Output
Elements in myList are [10, 20, 30, 40] Pop removes element 10 Elements in myList are [20, 30, 40]
1. Throws
NoSuchElementException if this list is empty
import java.util.*; class LinkedListPopNoSuch{ public static void main(String args[]){ LinkedList<Integer> myList; myList = new LinkedList<> (); System.out.println("Elements in myList are"); System.out.println(myList); System.out.print("Pop removes element "); System.out.println(myList.pop()); } }
Output
Elements in myList are [] Pop removes element Exception in thread "main" java.util.NoSuchElementException at java.util.LinkedList.removeFirst(LinkedList.java:268) at java.util.LinkedList.pop(LinkedList.java:799) at LinkedListPopNoSuch.main(LinkedListPopNoSuch.java:13)
No comments:
Post a Comment