gpt4 book ai didi

java.awt.Rectangle#intersects(Rectangle r) 丑陋的实现?

转载 作者:行者123 更新时间:2023-12-01 16:35:48 27 4
gpt4 key购买 nike

以下是intersects(Rectangle r) awt Rectangle 的方法 源代码。
我添加一些以 //* 开头的评论与我的问题相关:
由于代码验证 rw (例如)为正,则 rw rw+rx必须大于rx .
如果是这样rw < rx总是 false,那么为什么要检查它呢?

/**
* 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);
}

这同样适用于rh < rytw < txth < ty .

最佳答案

rw < rx 的测试, rh < ry , tw < txth < 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;
}

完成此操作后,我们可以更进一步,使代码更具可读性和简洁性:

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 ;
}

关于java.awt.Rectangle#intersects(Rectangle r) 丑陋的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61950929/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com