Win a copy of Rust Web Development this week in the Other Languages forum!
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:
• Tim Cooke
• Campbell Ritchie
• Ron McLeod
• Liutauras Vilda
• Jeanne Boyarsky
Sheriffs:
• Junilu Lacar
• Rob Spoor
• Paul Clapham
Saloon Keepers:
• Tim Holloway
• Tim Moores
• Jesse Silverman
• Stephan van Hulst
• Carey Brown
Bartenders:
• Al Hobbs
• Piet Souris
• Frits Walraven

# Understanding hashcode()

Ranch Hand
Posts: 75
• Number of slices to send:
Optional 'thank-you' note:
This question is from enthuware software:-

Which of the following options would satisfy the equals and hashCode contract at //1?

Option 1: return 0;
Option 2: return a;;
Option 3: return a+b;
Option 4:return a*a;
Option 5: return a/2;

Please help me understanding the hashcode as in this problem it is not clear to me what will be the output and why?

Ranch Hand
Posts: 1183
• Number of slices to send:
Optional 'thank-you' note:
The equals method must be Reflexive, Symmetric, Transitive and Consistent. That means:

Reflexive: x.equals(x) must be true
Symmetric: if x.equals(y) is true , then y.equals(x) must be true
Transitive: if x.equals(y) is true and x.equals(z) is true, then y.equals(z) must be true
Consistent: multiple calls to equals must return in the same result

Now as for hashCode(), there is one major rule:
If two objects are equal, the hashcode needs to be equal as well. The same however does not apply in reverse.

Given the information above you should be able to solve the question.

Sonali Sehgal
Ranch Hand
Posts: 75
• Number of slices to send:
Optional 'thank-you' note:
Hi Sebastian ,

I could not understand what are you trying to say on the hashcode???

Sebastian Janisch
Ranch Hand
Posts: 1183
• Number of slices to send:
Optional 'thank-you' note:
If two objects are equal (x.equals(y) == true), then x.hashCode() and y.hashCode() must return the same value.

However, if x.equals(y) == false, then x.hashCode() and y.hashCode() may return the same value.

It's as simple as that.

Greenhorn
Posts: 3
• Number of slices to send:
Optional 'thank-you' note:
Hello!

A very good explanation on hashcodes can be found in "SCJP Sun Certified Programmer for Java 6 Study Guide (Exam 310-065)" by Katherine Sierra, Bert Bates.

Ranch Hand
Posts: 5575
• Number of slices to send:
Optional 'thank-you' note:
Welcome to javaranch Narcisa

Ranch Hand
Posts: 352
• Number of slices to send:
Optional 'thank-you' note:
Is the answer offered Multiple choice?

Sonali Sehgal
Ranch Hand
Posts: 75
• Number of slices to send:
Optional 'thank-you' note:
@ Narcisa
I am already studying from Kathy Sierra