Thursday, 17 April 2014

HashSet : iterator : Returns an iterator to iterate the HashSet

public Iterator<E> iterator()
Returns an iterator over the elements in this set. 

import java.util.*;

class HashSetIterator{
 public static void main(String args[]){
  HashSet<Integer> mySet = new HashSet<> ();
  
  /* Add Elements to HashSet */
  mySet.add(10);
  mySet.add(20);
  mySet.add(30);
  mySet.add(40);
  
  Iterator<Integer> iter = mySet.iterator();
  
  System.out.println("Printing Set elements using iterator");
  while(iter.hasNext()){
   System.out.println(iter.next());
  }
 } 
}

Output
Printing Set elements using iterator
20
40
10
30

1. ConcurrentModificationException thrown if collection is modified by non iterator methods while iterating over it. You can update the Collection by iterator methods while iterating.

import java.util.*;

class HashSetIteratorConcurrent{
 public static void main(String args[]){
  HashSet<Integer> mySet = new HashSet<> ();
  
  /* Add Elements to HashSet */
  mySet.add(10);
  mySet.add(20);
  mySet.add(30);
  mySet.add(40);
  
  Iterator<Integer> iter = mySet.iterator();
  
  System.out.println("Printing Set elements using iterator");
  while(iter.hasNext()){
   System.out.println(iter.next());
   System.out.println("Adding data while iterating");
   mySet.add(90);
  }
 } 
}


Output
Printing Set elements using iterator
20
Exception in thread "main" java.util.ConcurrentModificationException
        at java.util.HashMap$HashIterator.nextEntry(HashMap.java:894)
        at java.util.HashMap$KeyIterator.next(HashMap.java:928)
        at HashSetIteratorConcurrent.main(HashSetIteratorConcurrent.java:17)

 
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment