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

Java | Difference between next() and hasNext() methods in collections: Here, we are writing the main difference between next() and hasNext() methods in java collections.
Submitted by IncludeHelp, on October 11, 2018

First of all, we should know, what is collection in java?

Collection in java represents a group of individual objects of same type like ArrayList, Vector, etc.

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.

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

Java List Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.