Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashSet doesn't guarantee sorting?

Tags:

java

import java.util.*;
public class DuplicateCheckMain {
 public static void main(String[] gopal){
  Integer[] args = {6,9,2,55,100,1,6,8,9};
  Integer[] args1 = {3,6,2,3,5};
  Set S = new HashSet();
  DuplicateCheck.checkDuplicate(S,args,new String("HashSet"));
  Set S1 = new HashSet();
  DuplicateCheck.checkDuplicate(S1,args1,new String("HashSet"));

  S = new TreeSet();
  DuplicateCheck.checkDuplicate(S,args,new String("TreeSet"));

  S = new LinkedHashSet();
  DuplicateCheck.checkDuplicate(S,args,new String("LinkedHashSet"));

 }
}

public class DuplicateCheck {

 public static void checkDuplicate(Set S, Integer[] args, String setname){
  for(int i = 0;i<args.length;i++){
   if(!S.add(args[i])){System.out.println("Duplicate element "+args[i]);}
  }
  System.out.println(S +" "+ setname);
 }
}

Question: for the HashSet with reference S, the HashSet is not sorted. But for the reference S1, the HashSet is sorted. Why so?

like image 911
Gopal Avatar asked Dec 12 '22 16:12

Gopal


2 Answers

HashSet is absolutely not guaranteed to be sorted. The ordering isn't guaranteed at all.

From the documentation of the iterator() method:

Returns an iterator over the elements in this set. The elements are returned in no particular order.

HashSet is designed to insert and check for the presence of elements very quickly, by equality. That's all.

If you need sorting, you should use an implementation of SortedSet, such as TreeSet or ConcurrentSkipListSet.

like image 168
Jon Skeet Avatar answered Dec 15 '22 04:12

Jon Skeet


HashSet used a mod to store the number into a bucket entry

In the args1 array all the number are less then 16 - the default HashSet size. that is why it ends up being sorted.

like image 31
The Scrum Meister Avatar answered Dec 15 '22 06:12

The Scrum Meister