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?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With