Java Programming - Objects and Collections - Discussion

Discussion Forum : Objects and Collections - Pointing out the correct statements (Q.No. 4)
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.
1 and 2
2 and 3
3 and 4
1 and 3
Answer: Option
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.

Discussion:
6 comments Page 1 of 1.

Charu said:   1 decade ago
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.
(1)

Arush said:   1 decade ago
Can anybody explain 4th one?

Arush said:   1 decade ago
Can anybody explain 4th one?

Przemulala said:   9 years ago
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:   9 years ago
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.

Pratik said:   6 years ago
Option C is incorrect. Hashcode method returns same value only if it called by same object.

Post your comments here:

Your comments will be displayed after verification.