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
-
3Why would you *not* want to use `equals`? Maybe comparing by identity is a bit faster, but is the extra speed actually meaningful? – Andy Turner Feb 17 '16 at 16:40
-
I'm a previous C++ user. I through that comparing using == is something like comaping addresses of JVM objects and should be faster than comapring by identity. Isn't so? – Ivan Feb 17 '16 at 16:42
-
Possible duplicate of [What is the fastest way to compare two sets in Java?](http://stackoverflow.com/questions/3341202/what-is-the-fastest-way-to-compare-two-sets-in-java) – hagmic Feb 17 '16 at 16:45
-
@Ivan It's faster, but it'll give you back a meaningless answer, so what's the point? It'd be faster to do nothing, but it's not like that'd help. – Louis Wasserman Feb 17 '16 at 18:09
-
Possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Ferrybig Feb 18 '16 at 09:35
1 Answers
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.

- 387,369
- 54
- 702
- 768