Wednesday 19 March 2014

Traverse Set

Iterator<E> iterator()
    Returns an iterator over the elements in this set. There is no guarantee that
the elements returned in the same order they inserted. The elements returned depends totally on the iterator.

import java.util.*;
class SetTraverse{
 public static void main(String args[]){
  Set<String> mySet = new HashSet<> ();
  
  /* Add Elements to set */
  mySet.add("String1");
  mySet.add("String2");
  mySet.add("String3");
  mySet.add("String4");
  
  /* Get an Iterator for the Set */
  Iterator iter = mySet.iterator();
  
  System.out.println("Elements in the mySet are");
  /* Traverse the set using iterator */
  while(iter.hasNext()){
   System.out.println(iter.next());
  }
 }
}

Output

Elements in the mySet are
String3
String4
String1
String2

As you observe the output, The Elements returned by the iterator are not exactly same as the way they inserted into the set.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment