Reputation: 1386
Given the following code:
public class NewClass {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("Orange", "Pineapple", "Banana", "Banana");
Set<String> fruitsSet = new HashSet<>();
for (String fruit : fruits) {
fruitsSet.add(fruit);
}
for (String fruit : fruitsSet) {
System.out.println(fruit);
}
}
}
Every time I run the code, the order of the elements is the same, eliminating the duplicate item Banana, as is typical of HashSet implementation:
Banana
Pineapple
Orange
My question is, why is the order the same every time, since the specification says "It makes no guarantees as to the iteration order of the set" (https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html)
Upvotes: 0
Views: 52
Reputation: 1
The iteration order in a hash set is determined by the way the hash function transforms each element to create it's hashCode. So for a specific string you'll get a specific hashCode and he will be placed in a specific cell of the Set.
No guarantees means that adding Orange , Pineapple and Banana will not guarantee that order while iterating.
Also, it leaves space for future implementations for HashSet by not committing to certain limitations ( such as ordering).
Upvotes: 0
Reputation: 937
The order in which HashSet
stores elements depends on the hashCode
of each element. Because each time you're placing the same String
s their hashCode
s are also the same and the order the same as well.
But as Louis Wasserman said you shouldn't rely on that order because there are no guarantees that it will not be changed in newer JDKs.
Upvotes: 0
Reputation: 198471
"No guarantees" means just that: no guarantees. It could be exactly the order you inserted the elements into the set, every time. It could be random order. It could be exactly the same order at all times except Tuesdays when it's a full moon. "No guarantees" does not mean "random" or "unpredictable," it just means you can't depend on any particular order because it could change for any reason.
Upvotes: 5