[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: hashCode question (was Re: Silly Java question)

From: Michael Barker
Subject: Re: hashCode question (was Re: Silly Java question)
Date: Wed, 28 Dec 2005 13:19:12 +0000

> The guidelines I've seen say that if two items are equal, then their
> hashcodes should match.  If they are unequal, their hashcodes should not
> match.
> I have implemented the equals function like so:
>   public boolean equals(Object that)
>   {
>     if (that == this)
>       return true;
>     if (! (that instanceof KerberosPrincipal))
>       return false;
>     // The other type must be the same or UNKNOWN.
>     if (((KerberosPrincipal)that).getNameType() != nameType)
>       if (((KerberosPrincipal)that).getNameType() != KRB_NT_UNKNOWN)
>         return false;
>     // The toString output must match.
>     if (! toString().equals(((KerberosPrincipal)that).toString()))
>       return false;
>     // Fallthrough case, we must be the same.
>     return true;
>   }
> But with a hashcode, I think I just have an int to compare, don't I?  I
> don't know how encode this type of logic into that.

>From the JDK docs:  

"If two objects are equal according to the equals(Object) method, then
calling the hashCode method on each of the two objects _must_ produce
the same integer result.

It is _not_ required that if two objects are unequal according to the
equals(java.lang.Object) method, then calling the hashCode method on
each of the two objects must produce distinct integer results. However,
the programmer should be aware that producing distinct integer results
for unequal objects may improve the performance of hashtables."

Given that the toString() must be the same in order to be equal then
your hashCode method could simply be:

public int hashCode()
  String s = toString();
  return (s != null) ? s.hashCode() : 0;

WRT performance, it will boil do to how often KerberosPrinicipals that
differ only by NameType be present in the same Hash(Table/Set/Map).

Michael Barker.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]