Java Programming - Objects and Collections - Discussion

4. 

What two statements are true about properly overridden hashCode() and equals() methods?

  1. hashCode() doesn't have to be overridden if equals() is.
  2. equals() doesn't have to be overridden if hashCode() is.
  3. hashCode() can always return the same value, regardless of the object that invoked it.
  4. equals() can be true even if it's comparing different objects.

[A]. 1 and 2
[B]. 2 and 3
[C]. 3 and 4
[D]. 1 and 3

Answer: Option C

Explanation:

(3) and (4) are correct.

(1) and (2) are incorrect because by contract hashCode() and equals() can't be overridden unless both are overridden.


Arush said: (Dec 22, 2014)  
Can anybody explain 4th one?

Arush said: (Dec 22, 2014)  
Can anybody explain 4th one?

Charu said: (Aug 23, 2015)  
4) equals() can be true even if it's comparing different objects.

Basically equals() method is use to compare two different object. And return true/false.

But if we are talking about hashcode() it returns "true" when object is same type. Against this statement equals() method can be "true" if we are comparing two different object but having same contains.

Przemulala said: (May 16, 2016)  
I've overridden only equals() and the code compiles and executes. Seems there's an error in the answers. OFC you should override both of them, but technically, it seems you don't have to do it mandatory.

Bix said: (Dec 24, 2016)  
So is this true? > Object().equals(new Object());.

If someone agrees on this statement then question must have been formulated differently. In contrary the question as it is inadequate.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.