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.
精彩评论