Can I only implement equals() but not hashCode() if I only need to compare objects and not yet plan to put the objects into any hash based containers?
Seems all Java bibles say these two MUST be implemented together. :(
My concerns: -If I always implement hashCode() together with equals() there will be lots of code not really used, and without unit test covering. (I'm not going to unit test hashCode() if not used) -It's only until when I put the object into a hash based container I know how the objects are intended to be looked up. And only until then I can be sure which hashing strategy to use.
Can I only implement equals() but not hashCode()?
Yes You can . Because they are just to method from the parent class
Object
, So it actually your choice to implement or not to (together or individual.)All Java bibles say these two MUST be implemented together.
If you are not using anything related to
hashcode
(as you said hash based container) it not aMUST
, But it is a good practice to implement them together to avoid any unexpected circumstances.