> Avi Kivity wrote:
> > class PrimaryKey {
> >     Type1 field1;
> >     Type2 field2;
> >
> >     boolean equals(Object other) {
> >         if (other == null || !(other instanceof
> PrimaryKey)) return false;
> >         PrimaryKey o = (PrimaryKey)other;
> >         return (field1 == o.field1 || field1 != null &&
> > field1.equals(o.field1))
> >             && (field2 == o.field2 || field2 != null &&
> > field2.equals(o.field2))
> >     }
> >
> >     int hashCode() {
> >         int ret = 0;
> >         if (field1 != null) ret += field1.hashCode();
> >         if (field2 != null) ret += field2.hashCode() * 127;
> >         return ret;
> >     }
> > }
>
> For performance purposes, wouldn't you want to do the
> calculation in the
> constructor? Something like:
>
> class PrimaryKey {
>   Type1 field1;
>   Type2 field2;
>
>   private int hashCode;
>
>   public PrimaryKey(field1, field2) {
>     if (field1 != null) hashCode += field1.hashCode();
>     if (field2 != null) hashCode += field2.hashCode() * 127;
>   }
>
>   public int hashCode() {
>     return hashCode;
>   }
> }
>

In the specific case of EJB primary keys, this is problematic. As the fields
must be accessible, there is no way to trap changes to them so the hash code
can be recalculated.

I wouldn't use this on non-immutable classes.

- Avi
--
s/\be(\w+)/e-\1/g;

===========================================================================
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff EJB-INTEREST".  For general help, send email to
[EMAIL PROTECTED] and include in the body of the message "help".

Reply via email to