0

Code.

Set<String> set = new HashSet<String>(3);
set.add("3 Lorem");
set.add("1 Lorem");
set.add("2 Lorem");
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
    String type = (String) iterator.next();
    System.out.println(type);
}

Output.

2 Lorem
3 Lorem
1 Lorem

This order looks strange to me. I add 3 Lorem, 1 Lorem, and then 2 Lorem. Why are they in a different order in the output?

Maksim Dmitriev
  • 5,985
  • 12
  • 73
  • 138

4 Answers4

9

Hash sets are not supposed to be sorted.

Technically they are sorted, but by the hash code (or a hash reduction thereof); and on hash collisions they may overflow into other buckets.

If you want an ordered set, use TreeSet instead. It usually is a bit slower, but sorted. If you want to retain the insertion order, use a List such as ArrayList or LinkedList.

There also is a hybrid, called LinkedHashSet, which allows fast contains operations, but maintains insertion order. Note that it won't have duplicates though.

Has QUIT--Anony-Mousse
  • 76,138
  • 12
  • 138
  • 194
5

From the JavaDocs:

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.

if you intended to keep order better use TreeSet (but complexity will be log(n)

also check this post Hashset vs Treeset

EDIT as pointed out by @Petar in order to maintain insertion order better use LinkedHashSet

and this Dzone Article demonstrates comparison between all three with nice suit of example and performance

Community
  • 1
  • 1
exexzian
  • 7,782
  • 6
  • 41
  • 52
3

Use a LinkedHashSet to maintain the insertion order.

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
1

Use TreeSet<String>(); or TreeSet<String>(String.CASE_INSENSITIVE_ORDER); if you want to Sort the elements. Use List instead of Set If you need to maintain the insertion order.

Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64