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)
HashSethas a constructor which makes that first loop unnecessary:new HashSet<>(fruits)