6

When i run the code which shown in below, the output is [50, 20, 5, 40, 10, 30]. I didn't understand this order. Why the output is not [10, 5, 20, 30, 40, 50] ?

List list = Arrays.asList(10, 5, 10, 20, 30, 40, 50);
System.out.println(new HashSet(list));
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
karlkeller
  • 1,251
  • 3
  • 12
  • 22

4 Answers4

6

Docs says

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.

go for LinkedHashSet

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • I don't want to sort. I read doc but when I tried two other computer I got the same output. If the order is not guaranteed, how it is same? – karlkeller Jun 27 '13 at 12:23
  • 1
    As you add and remove elements over time, the iteration order may change. You should never rely on the iteration order of Hashset, as it "makes no guarantees as to the iteration order," although in practice if you make a new Hashset with the default constructor and you add the same elements you end up with the same iteration order. – raptortech97 Jun 27 '13 at 12:28
  • raptortech you gave the answer which I was wondering and wanted to hear. thank you. – karlkeller Jun 27 '13 at 12:32
5

HashSet doesn't maintain insertion order. What you need is a LinkedHashSet.

Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
1

The HashSet class does not guarantee the order in which you have entered the data.

If you do not put your List in the HashSet and instead continue with List you will get the order in which you are adding the values in it.

You can use LinkedHashSet to keep the insertion order.

If you want to sort the List then you can use Collections.sort(). (Extra information, ignore if you do not need it)

JHS
  • 7,761
  • 2
  • 29
  • 53
0

From the doc

Java.util.HashSet 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.

stinepike
  • 54,068
  • 14
  • 92
  • 112