Results 1 to 2 of 2
Thread: the hashCode() contract
- 09-04-2011, 11:53 AM #1
the hashCode() contract
according to my scjp book (Exam 310-065) there are no hashCode requirements when x.equals(y) otherwise I would have a problem for a class Person that has a field name as String. Instantiating two Persons with new Person("May") and new Person("Amy") equals() returns true, but for me equals() should return false, since May and Amy are not the same. I override equals() so that each char is compared with the other char and if one comparison fails equals() returns false. So far all ok. but suppose you sould generate also a different hashCode for the two Strings May and Amy, how?
All other conditions and requirements for a valid hashCode() contract are clear!
Last edited by j2me64; 09-04-2011 at 11:59 AM.
- 09-04-2011, 01:00 PM #2
Re: the hashCode() contract
There's absolutely no requirement that different instances of the same class, for which equals(...) returns flase, must have differing hashCode. In fact, it's usually impossible, as the number of different, non-equal instances is usually more than Integer.MAX_VALUE.
A well distributed hashCode can however improve the performance of a hash based collection (Hashtable, HashMap etc). If you're never going to use instances of the class in a hash based collection, you might as well have hashCode() return 0 (or 1, or any constant).
For more, search the net for "hashcode collision"
- By Markgm in forum New To JavaReplies: 20Last Post: 08-14-2011, 04:37 PM
- By jomypgeorge in forum New To JavaReplies: 1Last Post: 02-10-2011, 08:34 AM
- By jomypgeorge in forum New To JavaReplies: 3Last Post: 01-14-2011, 12:32 PM
- By alpdog14 in forum New To JavaReplies: 3Last Post: 02-20-2010, 12:00 AM
- By email@example.com in forum New To JavaReplies: 7Last Post: 03-29-2009, 10:04 PM