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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Liutauras Vilda
• Tim Cooke
• Jeanne Boyarsky
• Bear Bibeault
Sheriffs:
• Knute Snortum
• paul wheaton
• Devaka Cooray
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Ron McLeod
• Piet Souris
• Ganesh Patekar
Bartenders:
• Tim Holloway
• Carey Brown
• salvin francis

# hashCode function

Ranch Hand
Posts: 62
i have the snippet of code od SCJP book
Which code, when inserted at (1), will provide a correct implementation of the
hashCode() method in the following program?

(a) return 31337;
(b) return accumulated / count;
(c) return (count << 16) ^ accumulated;
(d) return ~accumulated;
(e) return count == 0 ? 0 : average();
the correct answer is (a) and (e)
(b) is incorrect because of count if it is null it will genearte arithmetic Exception
but i don't now the mean of (c) and (d) and why are false

Marshal
Posts: 65474
249

emma roberts wrote:. . . (b) is incorrect because of count if it is null it will genearte arithmetic Exception

But count can't be null. It is a primitive and primtives can't be null. It might be 0, however, in which case you will get such an exception.

but i don't now the mean of (c) and (d) and why are false

Work out what will happen if your accumulated value is 288 and you have a count of 16. Then change the accumulated value to 289 and see what happens. Hint: 288 ÷ 16 = 18.

emma roberts
Ranch Hand
Posts: 62
please i still hava a difficult to undrestand the mean of (c) and (d) and why they are wrong

Master Rancher
Posts: 3322
31
• 1
For both (c) and (d), the problem is that they are not consistent with the implementation of equals().  You need to study how the equals() method is implemented, and compare that with the possible implementations of hashCode().  We can see that the equals() method uses count and average() - it doesn't use accumulated at all.  So right away, it should cause some concern if we see a hashCode() implementation that uses accumulated - such as b, c, or d.  The question is, is there any way that you can have two instances that are equal, as far as equals() is concerned, but have different hashcodes?  Because that is not allowed.

(The converse, instances that are not equal but have the same hashcode, is allowed - it's just inefficient.  So we ignore that case here.)

Consider two instances a and b:

What will happen if we run this, with code from (b), (c), or (d)? (Or (a) or (e)?)  Will the results make sense?  Try compiling and running the code yourself to see.

 Opportunity is missed by most people because it is dressed in overalls and looks like work - Edison. Tiny ad: Java file APIs (DOC, XLS, PDF, and many more) https://products.aspose.com/total/java