Method.hashCode() 是否考虑方法的参数类型?
Javadoc 说:
返回此方法的哈希码。哈希码被计算为底层方法的声明类名和方法名称的哈希码的异或。
此描述中明显缺少方法参数类型的类型 - 这是否意味着同一类上具有相同名称但参数不同的两个方法将具有相同的 hashCode()
?
The Javadocs say:
Returns a hashcode for this Method. The hashcode is computed as the exclusive-or of the hashcodes for the underlying method's declaring class name and the method's name.
Conspicuously absent from this description are the types of the Method's parameter types - does this mean that two methods on the same class with the same name, but different parameters, would have the same hashCode()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你是对的 - 如文档所述,具有相同名称和相同声明类的方法具有相同的哈希码。我同意,这有点违反直觉。
Sun 的 JDK 中的代码:
但是
hashCode()
并不是相等的标志。equals(..)
方法考虑参数。You are right - methods with the same name and the same declaring class have, as documented, the same hash-code. Which, I agree, is a bit counter-intuitive.
The code in Sun's JDK:
But
hashCode()
isn't a sign for equality. Theequals(..)
method takes into account arguments.让我们看看
比较
-319450075
比较
-319450075
索引
887779372
索引
887779372
索引
887779372
索引
887779372
...
Lets see
compareTo
-319450075
compareTo
-319450075
indexOf
887779372
indexOf
887779372
indexOf
887779372
indexOf
887779372
...
看来是这样。请注意,equals/hashCode 约定仍然保留,因为与 equals() 比较的两个方法将具有相同的 hashCode。
So it would seem. Note that the equals/hashCode contract is still preserved, in that two Methods that compare favorably with equals() will have the same hashCode.