Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

CelPal - SCJP 1.5 Part 3 - Question 26

 
Alam Ameghino
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given this fragment

Toll toll = new Toll();
Toll toll2 = new Toll();

What must be done so that the JVM understands whether toll and toll2 are the same or not ?

1.) Override public boolean hashCode() in Toll
2.) Override public int hashCode() in Toll
3.) Override public boolean toString() in Toll
4.) Override public boolean equals() in Toll
5.) Override public boolean equals(Object o) in Toll

The corret answers are 2) and 5), and the explication for the author is:

"The equals and hashCode methods must be overridden to compare any 2 objects"

But for me the unique answer correct is the number 5).

What do you think?

Thanks!

 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34837
369
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with 2 and 5. It is bad practice to implement equals() without implementing hashCode(). It breaks the contract of Java.

Also, the question doesn't specify how you are checking for equality. What if the objects are in a HashMap? Java will look at the hashcode first, see they are different and never get to calling equals
 
Alam Ameghino
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jeame, and thanks for your response!

I understand when you say "It is bad practice to implement equals() without implementing hashCode()" and I am agree with you. It's ok.

But, the question was: "What must be done so that the JVM understands whether toll and toll2 are the same or not?" and for me it enough only the answer 5).

About the options, for me:

5) We MUST do it
2) We SHOULD do it. It is correct, but it is not necesary.

What do you think? Am I wrong?

Here, an example:


A lot of thanks!
 
Paul Anilprem
Enthuware Software Support
Ranch Hand
Posts: 3760
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is not clear what is meant by "JVM understands" but assuming that the question is trying to compare the contents of the objects, option 5 is correct. Of course, as Jeanne said, it is a good practice to override hashCode if you are overriding equals, but from a strictly comparison perspective, overriding hashCode is not required.

HTH,
Paul.
 
Alam Ameghino
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul, Thanks for help us!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic