Method.hashCode() 是否考虑方法的参数类型?

发布于 2024-10-30 03:42:47 字数 180 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

温柔戏命师 2024-11-06 03:42:47

你是对的 - 如文档所述,具有相同名称和相同声明类的方法具有相同的哈希码。我同意,这有点违反直觉。

Sun 的 JDK 中的代码:

public int hashCode() {
    return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
}

但是 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:

public int hashCode() {
    return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
}

But hashCode() isn't a sign for equality. The equals(..) method takes into account arguments.

孤檠 2024-11-06 03:42:47

让我们看看

Method[] ms = String.class.getMethods();
for (Method method : ms) {
    System.out.println(method.getName());
    System.out.println(method.hashCode());
}

比较
-319450075

比较
-319450075

索引
887779372

索引
887779372

索引
887779372

索引
887779372
...

Lets see

Method[] ms = String.class.getMethods();
for (Method method : ms) {
    System.out.println(method.getName());
    System.out.println(method.hashCode());
}

compareTo
-319450075

compareTo
-319450075

indexOf
887779372

indexOf
887779372

indexOf
887779372

indexOf
887779372
...

拥抱没勇气 2024-11-06 03:42:47

看来是这样。请注意,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文