对于 HashMap,如果我只按键搜索,那么为值实现 hashCode() 会有帮助吗?

发布于 2024-09-30 00:53:52 字数 397 浏览 0 评论 0原文

我正在使用 Java 6。为了简单起见,一切都将是公开的。

假设我有这个简单的课程。

public class A{
    public String name;
    public String data;
}

我想将我的 A 类对象放入 HashMap 中。我将使用字段 name 作为键,将整个对象作为值。

我将仅按名称在此地图中搜索对象。

我的问题是,对于 A 类,我是否需要实现 hashCodeequals 用于查找目的?这会加快搜索速度吗?我知道这对 Sets 有帮助,但我不确定 HashMap 的键只是一个字符串。

I'm using Java 6. For simplicity, everything will be public.

Suppose I have this simple class.

public class A{
    public String name;
    public String data;
}

I want to put my class A objects into a HashMap. I will use the field name as the key, and the whole object as the value.

I will only search for an object in this map by name.

My question is, for class A, do I need to implement hashCode and equals for looking up purposes? Will that speed up the search at all? I know it would help for Sets, but I'm not sure about HashMaps whose key is just a String.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

这个俗人 2024-10-07 00:53:52

不需要,您只需要为键类型实现 hashCode 和 equals 即可。如果您只是将其存储为值,那么实现这些方法不会产生任何影响(对于性能或正确性)。

No, you only need to implement hashCode and equals for the key type. If you're just storing it as a value, implementing those methods will make no difference (to performance or correctness).

醉殇 2024-10-07 00:53:52

如果您只是使用 String 作为键,我认为您不需要担心实现这两种方法。但是,如果您计划使用 A 类作为密钥,则需要覆盖它们

I dont think you need to worry about implementing the 2 methods if you are jut using String as the key. You however need to override them both if you are planning to use Class A as the key

计㈡愣 2024-10-07 00:53:52

您只需支持 HashMap 中的键的 hashCodeequals 即可。由于密钥是一个字符串,而不是 A,因此无需实现这些 - 它们不会被使用。

You only need to support hashCode and equals for keys in a HashMap. Since the key is a string, and not an A, no need to implement those - they will not get used.

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