-4

Recently I came across this

String s = "9495963";
Set<Character> set = new HashSet<Character>();
for(char e : s.toCharArray()){
  set.add(e);
}
System.out.println(set);//[3, 4, 5, 6, 9]

The output i got was [3, 4, 5, 6, 9], so, if HashSet doesn't preserve any order then how come these numbers were arranged in the ascending order?

kjunz
  • 111
  • 1
  • 7
  • 3
    There is no _guarantee_ of order when iterating the hash set. That doesn't mean there is anything _wrong_ with you seeing those values in order. – Tim Biegeleisen Sep 18 '18 at 07:31
  • I understand both LinkedHashSet preserves insertion order and TreeSet rearrange to ascending order, but if HashSet is not ordered, then why that output? – kjunz Sep 18 '18 at 07:34
  • Use LinkedHashSet. this maintains the insertion order, TreeSet is used to get the sorted order of inserted elements. – Pandey Amit Sep 18 '18 at 07:37
  • @kjunz there are 5! (120) ways of arranging 5 things. The elements could appear in any one of those 120 ways; any one of them is equally valid. – Andy Turner Sep 18 '18 at 07:46

2 Answers2

7

Coincidence. It just happens that the hashCode of Character is it’s numeric value. If you keep adding more characters than there are hash buckets in the HashSet, you’ll see that they get out of order.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
2

HashSet uses a HashMap internally.

HashMap stores its elements in a hash table using each Object's hashCode() method.

For Character class, the hashcode is it's corresponding int value.

public static int hashCode(char value) {
    return (int)value;
}

For int and double datatypes, these are auto-boxed into the Integer and Double classes. When you make a HashSet of ints, it uses Integer's hashCode() method, which just returns the int. So if you add ints, they get stored in a sorted order.

But for double, Double's hashCode() method is much more complicated, because of the way doubles are represented in memory.

But, over time, when the elements exceed the bucket size, you'll see it won't maintain order.

Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86