User124235
User124235

Reputation: 147

Java hashset and treeset

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 ?

Upvotes: 3

Views: 117

Answers (3)

Piotr Wilkin
Piotr Wilkin

Reputation: 3501

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.

Upvotes: 1

Eran
Eran

Reputation: 394146

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.

Upvotes: 3

SpringLearner
SpringLearner

Reputation: 13854

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.

Upvotes: 3

Related Questions