Name: ________________________ Lab section: ____________________
public class Rectangle {
private int x, y, width, height;
public Rectangle(int x, int y, int width, int height) {
this.x = x; this.y = y;
this.width = width; this.height = height;
}
public void setDimens(int newWidth, int newHeight) {
this.width = newWidth;
this.height = newHeight;
}
public boolean equals(Object o) {
Rectangle other = (Rectangle)o;
}
public int hashCode() {
}
}
- Fill in equals and hashCode so that the
object works properly if equality between two Rectangles holds
iff they have the same perimeter. Thus, a 2×10 rectangle would
.equal a 6×6 rectangle because each has a perimeter of 24.
Yes, this is a strange notion of equality. Sacrifices must be made
for the sake of pedagogy. For hashCode, you will get
full credit if your implemenation is correct. You will get 10 extra points
if it also promotes efficiency.
- Consider use of a single Rectangle r in two threads.
One thread calls r.setDimens(2,2) and the other calls
r.setDimens(5,5). However, when both threads are done, the
dimensions are 2×5.
- Explain (on the back) how this could happen.
- How would you fix the Rectangle class so that
the dimensions are set atomically? After the threads complete,
the dimenions would then be either 2×2 or 5×5, but never
2×5.
Last modified 21:10:11 CST 18 January 2011
by Ron K. Cytron