对于 HashMap,如果我只按键搜索,那么为值实现 hashCode() 会有帮助吗?
我正在使用 Java 6。为了简单起见,一切都将是公开的。
假设我有这个简单的课程。
public class A{
public String name;
public String data;
}
我想将我的 A 类对象放入 HashMap 中。我将使用字段 name
作为键,将整个对象作为值。
我将仅按名称
在此地图中搜索对象。
我的问题是,对于 A 类,我是否需要实现 hashCode
和 equals
用于查找目的?这会加快搜索速度吗?我知道这对 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不需要,您只需要为键类型实现 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).
如果您只是使用 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
您只需支持 HashMap 中的键的
hashCode
和equals
即可。由于密钥是一个字符串,而不是A
,因此无需实现这些 - 它们不会被使用。You only need to support
hashCode
andequals
for keys in a HashMap. Since the key is a string, and not anA
, no need to implement those - they will not get used.