Q:

Difference between next() and hasNext() methods in Java collections

belongs to collection: Java List Programs

0

Method next() and hasNext()

Both are the library methods of Java.util.scanner class. Method hasNext() returns true / false - if collection has more values/elements, it returns true otherwise it returns false. Method next() returns the next element in the collection.

Difference between next() and hasNext()

Methods hasNext() returns true, if iterator has more elements and method next() returns the next element/object.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

import java.util.*;

public class ListExample {
  public static void main(String[] args) {
    //creating a list of integers
    List < Integer > int_list = new ArrayList < Integer > ();

    //adding some of the elements
    int_list.add(10);
    int_list.add(20);
    int_list.add(30);
    int_list.add(40);
    int_list.add(50);

    //printing elements
    System.out.println("List elements are...");
    //creating iterator
    Iterator < Integer > it = int_list.iterator();

    while (it.hasNext()) {
      System.out.println(it.next());
    }
  }
};

Output

List elements are...
10
20
30
40
50

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< Traverse the List elements using next() and hasNex...