Skip to content

Commit

Permalink
Simplify Rectangle.intersects (#302)
Browse files Browse the repository at this point in the history
Simplify and optimize the intersects checking method of Rectangle. Also
align the behavior of Rectangle.intersect for empty intersections.

Signed-off-by: Martin Jobst <[email protected]>
  • Loading branch information
mx990 authored Nov 22, 2023
1 parent 1592a00 commit 70c2969
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,14 @@ public void testIntersects() throws Exception {
assertFalse(rectangle1.intersects(new Rectangle(-100, -100, 10, 10)));
//
assertFalse(rectangle1.intersects(new Rectangle(0, 0, 5, 10)));
//
assertFalse(rectangle1.intersects(new Rectangle(15, 20, 0, 10)));
assertFalse(rectangle1.intersects(new Rectangle(15, 20, 10, 0)));
//
Rectangle rectangle3 = new Rectangle(0, 30, 0, 40);
assertFalse(rectangle3.intersects(rectangle3));
//
assertFalse(rectangle3.intersects(new Rectangle(0, 30, 100, 10)));
}

@SuppressWarnings("static-method")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -725,7 +725,7 @@ public Rectangle intersect(Rectangle rect) {
int x2 = Math.min(x + width, rect.x() + rect.width());
int y1 = Math.max(y, rect.y());
int y2 = Math.min(y + height, rect.y() + rect.height());
if (((x2 - x1) < 0) || ((y2 - y1) < 0)) {
if (((x2 - x1) <= 0) || ((y2 - y1) <= 0)) {
return setBounds(0, 0, 0, 0); // no intersection
}
return setBounds(x1, y1, x2 - x1, y2 - y1);
Expand All @@ -739,12 +739,9 @@ public Rectangle intersect(Rectangle rect) {
* @since 2.0
*/
public boolean intersects(Rectangle rect) {
int x1 = Math.max(x, rect.x());
int x2 = Math.min(x + width, rect.x() + rect.width());
int y1 = Math.max(y, rect.y());
int y2 = Math.min(y + height, rect.y() + rect.height());

return (((x2 - x1) > 0) && ((y2 - y1) > 0));
return width > 0 && height > 0 && rect.width() > 0 && rect.height() > 0 //
&& x < rect.x() + rect.width() && rect.x() < x + width //
&& y < rect.y() + rect.height() && rect.y() < y + height;
}

/**
Expand Down

0 comments on commit 70c2969

Please sign in to comment.