<p>hashCode implementation<p>
2 posts in topic
Flat View  Flat View

Posted By:   amit_anand
Posted On:   Friday, November 1, 2002 07:38 AM

What would be a reasonable hasCode implementation for a class containg two String variables.

I wrote it like this

public int hashCode() {

StringBuffer sbf = new StringBuffer();


String str = sbf.toString();

int hashCode = str.hashCode();

return hashCode;


Re: <p>hashCode implementation<p>

Posted By:   Paul_Holser  
Posted On:   Friday, November 1, 2002 12:12 PM

here's one that doesn't generate garbage.

public int hashCode() {
int result = 17;
result += 37 * ( (string1 == null) ? 0 : string1.hashCode() );
result += 37 * ( (string2 == null) ? 0 : string2.hashCode() );
return result;

Re: <p>hashCode implementation<p>

Posted By:   Christopher_Koenigsberg  
Posted On:   Friday, November 1, 2002 09:49 AM

Suppose you have 2 object instances of your class, say object A has (string1="X", string2=null) and object B has (string1=null, string2="X"). With your implementation, the hashcode will be the same value (the hashcode of "X"), for both A and B.

Or suppose object A has (string1="ab", string2="c") and object B has (string1="a", string2="bc"). Your hashcode for both of these will be equal (the hashcode of "abc") and will even be equal to the hashcode for object C (string1="abc", string2=null) and for object D (string1=null, string2="abc"), and so on....

Perhaps to handle all these cases, you could just put a special separator in the middle, of your "sbf"/"str", before taking its hashCode. Use something for the separator string, which you know will never occur in either string1 or string2.

About | Sitemap | Contact