CSE 331: Section 6 — Equals (Solutions)
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) |
Object.equals | true |
t.equals(u) |
Thing.equals | true |
o.equals(u) |
Object.equals | false |
u.equals(o) |
Object.equals | false |
u.equals((Thing) o) |
Thing.equals | true |
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; |
Yes | Collision: same width |
return color.hashCode(); |
No | Equal rectangles can differ in color |
return 42; |
Yes | Collision: all unequal pairs |
return width ^ height ^ color.hashCode(); |
No | Equal rectangles can differ in color |
return width ^ height; |
Yes | Collision: swapped dimensions, e.g. (2,3) and (3,2) |