0

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)

1
  • 1
    Just FYI, HashSet has a constructor which makes that first loop unnecessary: new HashSet<>(fruits) Commented Mar 29, 2017 at 21:04

3 Answers 3

5

"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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, I did a few tests and I notice that I change the JVM, the orders had changes
Yes, that's one reason it might change. Or a future JVM might deliberately randomize it. Or a future JVM might deliberately make it deterministic. Or a future JVM might detect when your application cares about ordering and then, and only then, randomize the ordering just to mess with you. No guarantees.
0

The order in which HashSet stores elements depends on the hashCode of each element. Because each time you're placing the same Strings their hashCodes 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.

Comments

0

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.