Overriding equals()
and
hashCode()
No. 161
Let me pass, please!
Q: |
Consider the following snippet:
Describe the above code's intended behaviour. Will it succeed? Execute the above code and provide a clue for correcting the underlying flaw. |
A: |
The user is being asked for a password. Only when entering
Unfortunately comparing the user's input and the corresponding password is seriously flawed:
On execution the string literal "secret" will be represented
as a Unfortunately the “==” operator only works as expected for the eight built in primitive Java™ types. With respect to class instances variables hold references to objects rather than to the objects' values. The “==” operator compares for object identity rather than for object equality. Two different final Scanner scan = new Scanner(System.in));
do {
System.out.print("Please enter password: ");
final String password = scan.nextLine();
if (password.equals("secret")) {
break; // Leave enclosing do ... while loop
} else {
System.out.println("Sorry, please try again");
}
} while (true);
System.out.println("You made it!");
// ... |
No. 162
Why is == correctly comparing enum
instances?
Q: |
The preceding exercise Let me pass, please! told us to override
Do we thus require an |
A: |
In case of Therefore for any two given MyEnum instance1 = MyEnum.x, // MyEnum representing instance2 = MyEnum.y; // some enum type. final boolean objectIdentity = (instance1 == instance2), // Both boolean values will objectEquality = instance1.equals(instance2); // always be equal. As an aside: In case of
|