简体   繁体   中英

Java - Best way to compare two Sets by hashes (via ==)

I have two Sets of Strings. Strings are the same ( == returns true ). I believe that comparing via == should be faster than comparing via equals() or hashCode() . So how to make sure they are the same not using equals() ? Thanks

Since the two Set s are not the same instance, you can't use == to compare the Set s.

Now, if you use Set 's equals , it (and by "it" I mean the default implementation of AbstractSet ) will validate the two Set s have the same size and then iterate over the elements of one Set and check if the other Set contains each of them.

If, for example, you are using HashSet s, in order to find if a String is contained in some HashSet , hashCode() will have to be used to find the bucket that may contain the searched String , but later String 's equals() will be called to validate the presence of a String equal to the searched String . String 's equals() actually begins with

    if (this == anObject) {
        return true;
    }

so the fact that your two Set s may contain references to the same String instance will be helpful in improving the runtime of the Set s comparison.

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