0

I read that java.util.HashSet doesn't sort. However when I execute this code

import java.util.*; 

public class Example {  
    public static void main(String[] args) { 
        Set set = new HashSet();  
        set.add(newInteger(5));  
        set.add(new Integer(2)); 
        set.add(new Integer(1)); 

        System.out.println(set);
    }
}

the output is

[1, 2, 5]

Why are the values sorted?

David Harkness
  • 35,992
  • 10
  • 112
  • 134
user2985842
  • 437
  • 9
  • 24

1 Answers1

0

There is no guarantee that it will always be in order. As already stated helpfully in the comments, it just so happens by chance that in this case does and if you are interested why check the Javadoc.

Essentially it uses a hash function (as you may have guessed by HashSet) to map the value to a particular 'bucket' or position in memory for fast look up (i.e. check set membership etc.). A simple example would be where it takes the value mod some number (i.e. number of 'buckets') to determine which 'bucket' to store the value which in your case is most likely is larger than the values of your added integers, hence they are placed in order.

xlm
  • 6,854
  • 14
  • 53
  • 55