java.util.HashSet iterator()
Description
The HashSet as majority of the Collection classes make use of Generics such that if we have declared our set like HashSet<String> set = new HashSet<String>() then the elements of inside our set is of type String otherwise a runtime error will be thrown.
Important notes for iterator() method:
- specified by iterator in interface Iterable<E>
- specified by iterator in interface Collection<E>
- specified by iterator in interface Set<E>
- specified by iterator in class AbstractCollection<E>
Method Syntax
public Iterator iterator()
Method Argument
Data Type | Parameter | Description |
---|---|---|
N/A | N/A | N/A |
Method Returns
The iterator() method returns an Iterator over the elements in this set.
Compatibility
Requires Java 1.2 and up
Java HashSet iterator() Example
Below is a java code demonstrates the use of iterator() method of HashSet class. The example presented might be simple however it shows the behavior of the iterator() method.
package com.javatutorialhq.java.examples; import static java.lang.System.*; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; /* * This example source code demonstrates the use of * iterator() method of HashSet class */ public class HashSetIteratorExample { public static void main(String[] args) throws InterruptedException { // get the HashMap object from the method init() HashSet studentSet = init(); // display the contents of our set Iterator it = studentSet.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } private static HashSet init() { // declare the HashSet object HashSet studentSet = new HashSet<>(); // put contents to our HashMap studentSet.add("Shyra Travis"); studentSet.add("Sharon Wallace"); studentSet.add("Leo Batista"); return studentSet; } }
This example is a lot simpler than it looks. First we have a method init() which generally populates a HashSet object and return it. This method has been called by the main method which then list down all the contents of the student set object using the iterator method(). As we have said earlier that a set is unsorted and it does not follow any pattern in displaying the elements. There is no guarantee on how the elements are arranged on the Set object. This is a common mistakes for most of beginners in java programming.