.hasNext()
Published Jun 30, 2022
Contribute to Docs
The .hasNext()
method returns true
if an Iterator
or a ListIterator
object has more elements. Returns false
otherwise.
Syntax
Boolean value = iterator.hasNext();
Where iterator
is an Iterator
or ListIterator
object.
Example
The following example uses an Iterator
to traverse an ArrayList
:
import java.util.*;public class Example {public static void main(String args[]) {// Create a new ArrayListArrayList l = new ArrayList();// Add some items to the ArrayListl.add(1);l.add(2);l.add(3);l.add(4);l.add(5);Iterator i = l.iterator();// Loop through ArrayList contentswhile(i.hasNext()) {Object item = i.next();System.out.print(item + ", ");}}}
This example outputs the following:
1, 2, 3, 4, 5,
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly16 hours