简体   繁体   中英

Why does this HashSet code snippet behave this way?

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 )

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM