1
    Set<Integer> set=new HashSet<Integer>();
    set.add(41);
    set.add(52);
    set.add(33);

    Iterator<Integer> iterate=set.iterator();
    System.out.println(iterate.next());
    System.out.println(iterate.next());
    System.out.println(iterate.next());

O/P-> 33 52 41 Instead I should get 41, 52 and 33

Plz explain why it is printing in this manner or I did something wrong.

Vihar
  • 3,626
  • 2
  • 24
  • 47
Samy
  • 73
  • 1
  • 11

1 Answers1

0

You must use LinkedHashSet to retain insertion order in your Set.
LinkedHashSet is designed to retain insertion order. From the JavaDocs:

Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

Kindly refer to the question Ordering of elements in Java HashSet to know about ordering in HashSet. From the JavaDocs:

This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.

Community
  • 1
  • 1
Ashish Kumar
  • 916
  • 2
  • 15
  • 32