• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

OCPJP 6 Practice exams, exam 1 q 57 bad/wrong explanation

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello everybody,
if you have a look at the question 57 in the first practice exam you'll find that the correct answer is C. However the explanation says "Because Stuff doesn't override equals()". This is actually true but it should say "Because Stuff doesn't override equals() and hashcode()". Because if the class Stuff doesn't override hashcode() as well, the objects are all different.
So let's imagine we override equals like this:

public boolean equals(Object obj) {
return this.value == ((Stuff) obj).value;
}

Even in this case, if we don't override the hashcode method, the set will add every new object in a different hashcode bucket and won't execute equals() against any other object. If we override the hashcode like this:

public int hashCode() {
return 4;
}

Even though this is a very inefficient override of the hashcode method (every object will be in the same bucket) the set will be able to compare the objects.

Regards!
 
He was giving me directions and I was powerless to resist. I cannot resist this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic