Reputation: 745
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?
Upvotes: 4
Views: 5506
Reputation: 7778
Please note that beyond not guarantying sorting, HashSet
s iteration order may change completely if you insert new elements. For instance:
public class TestHashSet {
public static void main(String[] foo) {
Set<Integer> set = new HashSet<Integer>();
set.addAll(Arrays.asList(new Integer[] {6,9,2,55,100,1,6,8,9}));
System.out.println(set);
set.addAll(Arrays.asList(new Integer[] {7,3,13,37,66}));
System.out.println(set);
set.add(42);
System.out.println(set);
}
}
Gave me the following output:
[1, 100, 2, 55, 6, 8, 9]
[1, 100, 2, 3, 55, 66, 6, 37, 7, 8, 9, 13]
[1, 2, 100, 3, 6, 66, 7, 37, 8, 42, 9, 13, 55]
Notice how the insertion of a single element changed completely the order.
Upvotes: 3
Reputation: 32004
java.util.Set
guarantees "no duplicate elements".
java.util.SortedSet
guarantees ordering and "no duplicate elements".
Upvotes: 0
Reputation: 1500495
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
.
Upvotes: 7
Reputation: 30111
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.
Upvotes: 3
Reputation: 41097
HashSet
does not guarantee sorting. To have sorting feature, use TreeSet
or something similar.
Upvotes: 0