Java Iterator hasNext() Method
Example
Loop through a list with hasNext() and next():
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
Iterator<String> it = cars.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
Definition and Usage
The hasNext() method returns true if there are more items to loop through, and false when the iterator has reached the end.
It is often used as the condition of a while loop, together with next().
Tip: Use the next() method to get the next item.
Syntax
public boolean hasNext()
Parameter Values
None.
Technical Details
| Returns: | true if there are more items, otherwise false. |
|---|
Related Pages
❮ Iterator Methods