Difference between next() and hasNext() in java collections?


Java provides Iterator and ListIterator classes to retrieve the elements of the collection objects.

The hasNext() method

The hasNext() method of these interfaces returns true if the collection object has the next element else it returns false.

Example

 Live Demo

import java.util.ArrayList;
import java.util.Iterator;
public class hasNextExample{
   public static void main(String[] args){
      ArrayList <String> list = new ArrayList<String>();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      Iterator<String> it = list.iterator();
      System.out.println(it.hasNext());
      it.next();
      System.out.println(it.hasNext());
      it.next();
      System.out.println(it.hasNext());
   }
}

Output

true
true
false

The next() method

The next() methods of the Iterator and ListIterator returns the next element of the collection.

Example

 Live Demo

import java.util.ArrayList;
import java.util.Iterator;
public class nextExample{
   public static void main(String[] args){
      ArrayList <String> list = new ArrayList<String>();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      list.add("OpenNLP");
      list.add("JOGL");
      list.add("Hadoop");
      list.add("HBase");
      list.add("Flume");
      list.add("Mahout");
      list.add("Impala");
      System.out.println("Contents of the array list (first to last): ");
      Iterator<String> it = list.iterator();
      while(it.hasNext()) {
         System.out.println(it.next());
      }
   }
}

Output

Contents of the array list (first to last):
JavaFX
Java
WebGL
OpenCV
OpenNLP
JOGL
Hadoop
HBase
Flume
Mahout
Impala

Updated on: 15-Oct-2019

884 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements