Java Programming - Objects and Collections - Discussion

Discussion Forum : Objects and Collections - Pointing out the correct statements (Q.No. 5)
5.
Which two statements are true about comparing two instances of the same class, given that the equals() and hashCode() methods have been properly overridden?
  1. If the equals() method returns true, the hashCode() comparison == must return true.
  2. If the equals() method returns false, the hashCode() comparison != must return true.
  3. If the hashCode() comparison == returns true, the equals() method must return true.
  4. If the hashCode() comparison == returns true, the equals() method might return true.
1 and 4
2 and 3
3 and 4
1 and 3
Answer: Option
Explanation:

(1) is a restatement of the equals() and hashCode() contract. (4) is true because if the hashCode() comparison returns ==, the two objects might or might not be equal.

(2) and (3) are incorrect because the hashCode() method is very flexible in its return values, and often two dissimilar objects can return the same hash code value.

Discussion:
4 comments Page 1 of 1.

Devdyuti singh` said:   9 years ago
C is the right answer, because when == operator matches the object initiated in heap or string pool is locating the same address or nor.

If there are 2 instances are == operator will give true while equals method return false;

Ex:

String s1=new String("Dev");
String s2=new String("Dev");

s1==s2 is false
s1.equals is true

Check it out.

AKASH SHARMA said:   1 decade ago
Answer is not correct, lets see this example:

Here equals() method return true but hashcode() method return false.

class A
{
public static void main(String args[])
{
String a="akash";
String b=new String ("akash");
boolean c=a.equals(b);
boolean d=a==b;
System.out.println (c);
System.out.println (d);
}
}

Rishabh Rastogi said:   8 years ago
B is the right answer.

Abc said:   1 decade ago
I don't understand!

Post your comments here:

Your comments will be displayed after verification.