> -----Original Message-----
> From: A mailing list for Enterprise JavaBeans development 
> [mailto:[EMAIL PROTECTED]] On Behalf Of Juan Pablo Lorandi

>     public boolean equals(Object obj)
>     {
>         AlbumTrackBeanPK pkObj=(AlbumTrackBeanPK)obj;
>         return (albumId==(pkObj.albumId) && 
> trackId==(pkObj.trackId) );
>     }

This is a dangerous implementation that can throw ClassCastException.
Here is a safer one:

  public boolean equals(Object other) {
    if (other == this) return true;
    if (null == other) return false;
    if (other.hashCode() != hashCode()) return false;
    try {
      TrackBeanPK other2 = (TrackBeanPK) other;
       return this.albumID.equals(other2.albumID) &&
this.trackId.equals(other2.trackId);
    }
    catch(ClassCastException ex) {
      return false;
    }
  }

Note that this implementation is optimized in several ways:

- Check for obvious cases first
- Assume that in most cases, the two objects being compared will be of
the same class
 
>     public int hashCode()
>     {
>         try
>         {
>             long    crcKey = -1;
>             java.io.ByteArrayOutputStream bos = new 
> java.io.ByteArrayOutputStream();
>             java.io.ObjectOutputStream oos = new 
> java.io.ObjectOutputStream(bos);
>             oos.writeObject(this);
>             oos.flush();
>             java.util.zip.Adler32 adl32 = new java.util.zip.Adler32();
>             adl32.update(bos.toByteArray());
>             crcKey = adl32.getValue();
>             return (int)(crcKey ^ (crcKey >> 32));
>         } catch (java.io.IOException ioEx)
>         {
>             return -1;
>         }
> 
>     }
> }

Also, note that using ObjectOutputStream for hashcode() might be
serializing more than is needed (e.g. FatKey pattern).

-- 
C�dric

==========================================================================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