开发者

For HashMap, would implementing hashCode() for the value help if I only search by key?

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.


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).


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜