3

I have a question. It says that hashset in java doesn't mantain an order but looking at my program

public static void main(String[] args) {
    HashSet<Integer> io=new HashSet<Integer>();

    Integer io1=new Integer(4);
    Integer io2=new Integer(5);
    Integer io3=new Integer(6);

    io.add(io2);
    io.add(io3);
    io.add(io1);

    System.out.println(io);
}

and execute it it give me an ordered set everytime i run it. Why this is happening?

Another question is: if i implement a treeset (like i did in the previous program but instead of hashset using treeset and intead of Integer using my class) i have to implement compareto ?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
User124235
  • 147
  • 8

3 Answers3

3

As per oracle docs, there is no guarantee that you will get the same order all the time.

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.

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
  • I don't think this answers the question. The question is WHY do we get the same order every time we run the program; not whether the documentation of `HashSet` guarantees that we will do so. – Dawood ibn Kareem Aug 03 '16 at 13:43
3

HashSet doesn't maintain order, but it has to iterate over the elements in some order when you print them. HashSet is backed by a HashMap, which iterates over the elements in the order of the bins in which they are stored. In your simple example, 4,5,6 are mapped to bins 4,5,6 (since the hashCode of an integer is the value of the integer) so they are printed in ascending order.

If you tried to add 40,50,60 you would see a different order ([50, 40, 60]), since the default initial number of bins is 16, so the hash codes 40,50,60 will be mapped to bins 40%16 (8),50%16 (2) ,60%16 (12), so 50 is the first element iterated, followed by 50 and 60.

As for TreeSet<SomeCostumClass>, you can either implement Comparable<SomeCostumClass> in SomeCostumClass, or pass a Comparator<SomeCostumClass> to the constructor.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

A HashSet keeps an internal hash table (https://en.wikipedia.org/wiki/Hash_table), which is driven by the result of the respective objects hashCode(). For most objects, the hashCode() function is deterministic, so the results of iterating a HashSet of the same elements will likely be the same. That does not mean it will be ordered. However, for Integer specifically, the hashCode() of the function returns the very integer itself, therefore, for a single-level hash table it will be ordered.

Piotr Wilkin
  • 3,446
  • 10
  • 18