简体   繁体   English

Java-通过哈希比较两个Set的最佳方法(通过==)

[英]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. 现在,如果您使用Setequals ,它将(并且通过“ 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的存储桶,但后来Stringequals()将被调用以验证是否存在与搜索到的String相等的String String 's equals() actually begins with Stringequals()实际上以

    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.

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