[英]Java - Best way to compare two Sets by hashes (via ==)
I have two Sets of Strings. 我有两组字符串。 Strings are the same ( ==
returns true
). 字符串是相同的( ==
返回true
)。 I believe that comparing via ==
should be faster than comparing via equals()
or hashCode()
. 我相信通过==
进行比较应该比通过equals()
或hashCode()
进行比较更快。 So how to make sure they are the same not using equals()
? 那么如何不使用equals()
确保它们相同呢? Thanks 谢谢
Since the two Set
s are not the same instance, you can't use ==
to compare the Set
s. 由于两个Set
不是同一实例,因此不能使用==
来比较Set
。
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. 现在,如果您使用Set
的equals
,它将(并且通过“ it”,我的意思是AbstractSet
的默认实现)将验证两个Set
的大小相同,然后遍历一个Set
的元素并检查另一个Set
包含每个。
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
. 例如,如果您使用的是HashSet
,则为了查找某个HashSet
是否包含String
,必须使用hashCode()
来查找可能包含搜索到的String
的存储桶,但后来String
的equals()
将被调用以验证是否存在与搜索到的String
相等的String
。 String
's equals()
actually begins with String
的equals()
实际上以
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. 因此您的两个Set
可能包含对同一String
实例的引用这一事实将有助于改善Set
的比较的运行时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.