Skip to main content

CSE 331: Section 6 — Equals

Task 1 — Thing 1 and Thing 2

Consider the following class Thing, which, unfortunately, doesn't properly override equals, but overloads it instead.

class Thing {
  private int contents;

  public Thing(int value) {
    this.contents = value;
  }

  public boolean equals(Thing other) {
    return this.contents == other.contents;
  }
}

For each method call, indicate which equals method runs, and whether it prints true or false.

public static void main(String[] args) {
  Thing t = new Thing(17);
  Object o = t;
  Thing u = new Thing(17);

  // Method called       Output
  System.out.println(t.equals(o));
  System.out.println(t.equals(u));
  System.out.println(o.equals(u));
  System.out.println(u.equals(o));
  System.out.println(u.equals((Thing) o));
}
Method call Method called Output
t.equals(o)
t.equals(u)
o.equals(u)
u.equals(o)
u.equals((Thing) o)

Task 2 — Wrecked Angle

Here is a small class with a correctly overridden equals method.

public class ColoredRectangle {
  private int width;
  private int height;
  private String color;

  /** Equality for ColoredRectangles. Two ColoredRectangles
   *  are the same if they have the same width and height.
   */
  @Override
  public boolean equals(Object o) {
    if (! (o instanceof ColoredRectangle)) {
      return false;
    }
    ColoredRectangle cr = (ColoredRectangle) o;
    return this.width == cr.width && this.height == cr.height;
  }

  // public int hashCode() { *** implementation here *** }
}

For each possible implementation of hashCode, answer whether it satisfies the hashCode contract. If yes, identify one type of collision between unequal rectangles. If no, explain why. Recall that ^ is bitwise XOR.

Implementation Satisfies contract? Collision
return width;
return color.hashCode();
return 42;
return width ^ height ^ color.hashCode();
return width ^ height;