Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equals() without hashCode()

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.

like image 402
twu Avatar asked May 04 '15 08:05

twu


People also ask

Can we override equals without hashCode?

You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.

What happens if we do not override hashCode () and equals () in HashMap?

If you don't override hashcode() then the default implementation in Object class will be used by collections. This implementation gives different values for different objects, even if they are equal according to the equals() method.

Does equals method use hashCode?

Java hashCode() An object hash code value can change in multiple executions of the same application. If two objects are equal according to equals() method, then their hash code must be same. If two objects are unequal according to equals() method, their hash code are not required to be different.

Why do we need hashCode and equals method in java?

The equals() and hashcode() are the two important methods provided by the Object class for comparing objects. Since the Object class is the parent class for all Java objects, hence all objects inherit the default implementation of these two methods.


1 Answers

You can, but you'll be breaking the general contract of equals, and this will lead to weird bugs. Even if you don't think you're using the hash codes, any external code you pass the objects to might rely on them, even if it doesn't seem to be hash-based. If you're not going to give your objects a decent hash method, at least make it throw a runtime exception. It's almost always better to give your objects a decent hashCode, though.

like image 83
user2357112 supports Monica Avatar answered Oct 07 '22 15:10

user2357112 supports Monica