Reputation: 33
I just started learning about sets, and it was mentioned that it did not care about order, unlike lists.
However, when I typed this piece of code:
public class test {
public static void main(String[] args) {
Set<Integer> nums = new HashSet<Integer>();
nums.add(0);
nums.add(1);
nums.add(2);
nums.add(3);
for (Integer num : nums)
System.out.println(num);
}
}
Based on the first line, the output should have been random, but instead it gave ordered output:
0
1
2
3
I have tried scrambling the order at which the numbers are being added, like this:
public class test {
public static void main(String[] args) {
Set<Integer> nums = new HashSet<Integer>();
nums.add(1);
nums.add(0);
nums.add(3);
nums.add(2);
for (Integer num : nums)
System.out.println(num);
}
}
Oddly though, the output was still ordered!
Is there anything that somehow sorts the set before I print its elements out?
Or is HashSet
not meant for creating unordered sets?
Upvotes: 1
Views: 1672
Reputation: 2939
HashSet is unordered by design. You are putting only limited small numbers which produce hash code of the value in same order. That's why it is printing in order. See the code below to see hash code and analyze it
for (Integer num : nums){
System.out.println(num + " - hashcode = " +num.hashCode());
}
Add few more large numbers to see unordered nature in action.
Example:
nums.add(29000);
nums.add(199201);
Upvotes: 0
Reputation: 1075159
HashSet
doesn't provide any order guarantees. That doesn't mean that order can't emerge, for some data sets, as a by-product of how it is implemented. Just that you cannot rely on that, and it may change from implementation to implementation, etc.
Upvotes: 1
Reputation: 311978
A HashSet
is indeed an unsorted set. This means you can't assume anything about the order it's iterated over (and printed) - the same way you can't assume it will be ordered, you also can't assume it won't be. The order is completely up to the internal implementation.
Upvotes: 0
Reputation: 3591
This is just a coincidence (or actually it's because how the HashSet
internally works but don't care about that for now). Try adding a few more values and then removing and then adding etcetera and you will see that it doesn't print correctly. HashSet
is unordered. Sets in general are unordered unless it is stated otherwise.
Upvotes: 0