In Java objects are stored dynamically using objects. Now in order to traverse across these objects is done using a for-each loop, iterators, and comparators. Here will be discussing iterators. The Interface allows visiting elements in containers one by one which indirectly signifies retrieval of elements of the collection in forwarding direction only.
Interface compromises of three methods :
(A) hasNext() Method
hasNext() method is used to check whether there is any element remaining in the List. This method is a boolean type method that returns only true and false as discussed as it is just used for checking purposes. The hasNext() methods of the Iterator and List Iterator returns true if the collection object over which is used to check during traversal whether the pointing element has the next element. If not it simply returns false. So,
Return Value: True - if iteration has more elements False - if iteration has no more elements
Return type: boolean
true true false
(B) next() method
If there is an element after where hasNext() has returned false on which some execution is to be performed then this method is used to display that element on which execution is supposed to be carried on with help of this method. The next() methods of the Iterator and List Iterator returns the next element of the collection. And if there is a need to remove this element remove() method is used.
Return type: Same as collection such as ArrayList, Linked List, etc.
Return value: The next element in the iteration.
Exception: Throws NoSuchElementException if the iteration has no more elements.
Element1 Element2 Element3
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.