[英]java.awt.Rectangle#intersects(Rectangle r) ugly implementation?
The following is intersects(Rectangle r)
method from awt Rectangle source code.以下是来自 awt Rectangle源代码的
intersects(Rectangle r)
方法。
I add some comments starting with //*
related to my question:我添加了一些与我的问题相关的以
//*
开头的评论:
Since the code verifies that rw (for example) is positive then rw rw+rx
must be bigger than rx
.由于代码验证 rw (例如)为正,因此 rw
rw+rx
必须大于rx
。
If that is the case rw < rx
is always false, so why is it checked?如果是这种情况
rw < rx
总是错误的,那么为什么要检查它呢?
/**
* Determines whether or not this {@code Rectangle} and the specified
* {@code Rectangle} intersect. Two rectangles intersect if
* their intersection is nonempty.
*
* @param r the specified {@code Rectangle}
* @return {@code true} if the specified {@code Rectangle}
* and this {@code Rectangle} intersect;
* {@code false} otherwise.
*/
public boolean intersects(Rectangle r) {
int tw = width;
int th = height;
int rw = r.width;
int rh = r.height;
if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) return false;
int tx = x;
int ty = y;
int rx = r.x;
int ry = r.y;
//*at this point rw must be positive
rw += rx; //*after this assignment rw must be bigger than rx
rh += ry;
tw += tx;
th += ty;
// overflow || intersect
return (rw < rx || rw > tx) && //*rw < rx should always be false
(rh < ry || rh > ty) &&
(tw < tx || tw > rx) &&
(th < ty || th > ry);
}
The same applies to rh < ry
and tw < tx
and th < ty
.这同样适用于
rh < ry
和tw < tx
和th < ty
。
The test for rw < rx
, rh < ry
, tw < tx
and th < ty
are redundant and can be eliminated: rw < rx
、 rh < ry
、 tw < tx
和th < ty
的测试是多余的,可以消除:
public boolean intersects(Rectangle r) {
int tw = width;
int th = height;
int rw = r.width;
int rh = r.height;
if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0)return false;
rw += r.x;
rh += r.y;
tw += x;
th += y;
return rw > x &&
rh > y &&
tw > r.x &&
th > r.y;
}
After doing that we can take it one step further, make the code more readable and concise:这样做之后,我们可以更进一步,使代码更具可读性和简洁性:
public boolean intersects(Rectangle other) {
//to intersect both vertical and horizontal edges need to cross
return
//check if horizontal edge cross
other.width + other.x > x && //other max x is bigger than min x and
other.x < width + x && //other min x is smaller than max x
//check if vertical edge cross
other.height+ other.y > y &&
other.y <height + y ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.