java.awt.Rectangle#intersects(Rectangle r)难看的实现? [英] java.awt.Rectangle#intersects(Rectangle r) ugly implementation?

查看:219
本文介绍了java.awt.Rectangle#intersects(Rectangle r)难看的实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是来自awt intersects(Rectangle r)方法.java"rel =" nofollow noreferrer>矩形 源代码.
我添加了一些与问题有关的以//*开头的评论:
由于代码验证rw(例如)为正,因此rw rw+rx必须大于rx.
如果是这种情况,rw < rx始终为false,那么为什么要对其进行检查?

The following is intersects(Rectangle r) method from awt Rectangle source code.
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.
If that is the case rw < rx is always false, so why is it checked ?

/**
 * 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 < rxrh < rytw < txth < ty的测试是多余的,可以删除:

The test for rw < rx , rh < ry, tw < tx and th < ty are redundant and can be eliminated:

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

这篇关于java.awt.Rectangle#intersects(Rectangle r)难看的实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆