Home
Aptitude
Categories


Home » Java programs » Java list programs

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.