Maksim Dmitriev
Maksim Dmitriev

Reputation: 6209

Unsorted HashSet in Java

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?

Upvotes: 0

Views: 12263

Answers (4)

exexzian
exexzian

Reputation: 7890

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

Upvotes: 5

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

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.

Upvotes: 1

Petar Minchev
Petar Minchev

Reputation: 47373

Use a LinkedHashSet to maintain the insertion order.

Upvotes: 3

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77454

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.

Upvotes: 9

Related Questions