View RSS Feed

Advanced Java

Comparing Objects and HashCode

Rate this Entry
by , 11-29-2011 at 10:30 PM (3601 Views)
Another thing that many programmers forget when they make objects that they need to compare in their applications is that it is not enough to assume that if your object is a subclass of Object, that the hashCode method that you can use it in a HashMap, Hashtable or HashSet. In fact, the Java specification states that you must always override the hashCode when ever you override the equals method. Otherwise, you have violated one of the key tenants of Java in not ensuring that equal objects have equal hash codes.

This is a class that is a subclass of Object and implements an interface Entity<Cargo>. Based on Domain Driven Design model.

Java Code:
public class Cargo implements Entity<Cargo> {

  private TrackingId trackingId;
  private Location origin;
  private RouteSpecification routeSpecification;
  private Itinerary itinerary;
  private Delivery delivery;

  public Cargo(final TrackingId trackingId, final RouteSpecification routeSpecification) {
    Validate.notNull(trackingId, "Tracking ID is required");
    Validate.notNull(routeSpecification, "Route specification is required");

    this.trackingId = trackingId;
    // Cargo origin never changes, even if the route specification changes.
    // However, at creation, cargo orgin can be derived from the initial route specification.
    this.origin = routeSpecification.origin();
    this.routeSpecification = routeSpecification;

    this.delivery = Delivery.derivedFrom(
      this.routeSpecification, this.itinerary, HandlingHistory.EMPTY
    );
  }

  /**
   * The tracking id is the identity of this entity, and is unique.
   * 
   * @return Tracking id.
   */
  public TrackingId trackingId() {
    return trackingId;
  }

  /**
   * @return Origin location.
   */
  public Location origin() {
    return origin;
  }

  /**
   * @return The delivery. Never null.
   */
  public Delivery delivery() {
    return delivery;
  }

When we produce a good hash function it tends to produce unequal hash codes for unequal objects. The code shown above and below fulfills all of the three provisions of the hashCode contract.

Java Code:
 /**
   * @param object to compare
   * @return True if they have the same identity
   * @see #sameIdentityAs(Cargo)
   */
  @Override
  public boolean equals(final Object object) {
    if (this == object) return true;
    if (object == null || getClass() != object.getClass()) return false;

    final Cargo other = (Cargo) object;
    return sameIdentityAs(other);
  }

  /**
   * @return Hash code of tracking id.
   */
  @Override
  public int hashCode() {
    return trackingId.hashCode();
  }

Submit "Comparing Objects and HashCode" to Facebook Submit "Comparing Objects and HashCode" to Digg Submit "Comparing Objects and HashCode" to del.icio.us Submit "Comparing Objects and HashCode" to StumbleUpon Submit "Comparing Objects and HashCode" to Google

Comments