This java example shows how to display all elements in a Java HashSet object using Iterator and for-each loop.
import java.util.HashSet; import java.util.Iterator; public class DisplayAllElementsInHashSetExample { public static void main(String[] args) { // create an HashSet object HashSet hashSet = new HashSet(); // Add elements to HashSet hashSet.add(1); hashSet.add(2); hashSet.add(3); System.out.println("HashSet contains : "); System.out.println("Display elements using Iterator."); Iterator i = hashSet.iterator(); while (i.hasNext()) { System.out.println(i.next()); } System.out .println("Display elements using for-each loop(available since jdk1.5)"); for (Object e : hashSet) { System.out.println(e); } } }
The output is:
HashSet contains :
Display elements using Iterator.
1
2
3
Display elements using for-each loop(available since jdk1.5)
1
2
3
No comments:
Post a Comment