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