使用hashCode()测试字符串相等性 [英] Testing string equality using hashCode()

查看:126
本文介绍了使用hashCode()测试字符串相等性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有理由不能使用hashCode方法测试Java字符串的相等性?所以基本上,而不是....

Is there any reason why a Java string cannot be tested for equality using it's hashCode method? So basically, instead of....

"hello".equals("hello")

您可以使用...

"hello".hashCode() == "hello".hashCode()

这将是有用,因为一旦字符串计算了它的哈希码,那么比较一个字符串就像比较一个int一样有效,因为字符串缓存了哈希码,而且如果你那样设计它,很可能字符串在字符串池中。 / p>

This would be useful because once a string has calculated it's hashcode then comparing a string would be as efficient as comparing an int as the string caches the hashcode and it is quite likely that the string is in the string pool anyway, if you designed it that way.

推荐答案

因为:如果对象相等,两个对象的hashCodes必须相等,但是,如果两个对象不相等,hashCode可以仍然是平等的。

because: hashCodes of two objects must be equal if the objects are equal, however, if two objects are unequal, the hashCode can still be equal.

(评论后修改)

这篇关于使用hashCode()测试字符串相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆