是否可以在一次通话中退回多个项目?

Ale*_*lex 0 java

是否有可能以下元素在一次调用中返回多个项目(即两个GRects)

    private GObject getColidingObject(){
    if(getElementAt(ball.getX(), ball.getY()) != null){
        return getElementAt(ball.getX(), ball.getY());
    }else if(getElementAt(ball.getX() + BALL_RADIUS *2, ball.getY()) != null){
        return getElementAt(ball.getX() + BALL_RADIUS *2, ball.getY());
    }else if(getElementAt(ball.getX(), ball.getY() + BALL_RADIUS *2) != null){
        return getElementAt(ball.getX(), ball.getY() + BALL_RADIUS *2);
    }else if(getElementAt(ball.getX() + BALL_RADIUS *2, ball.getY() + BALL_RADIUS *2) != null){
        return getElementAt(ball.getX() + BALL_RADIUS *2, ball.getY() + BALL_RADIUS *2);
    }else{
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 9

您只能返回一个值,但您可以将该值设为数组.例如:

private GObject[] getCollidingObjects() {
    GObject[] ret = new GObject[2];

    ret[0] = ...;
    ret[1] = ...;
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,当你开始在同一个方法中多次重复使用同一个表达式时,你应该考虑引入一个局部变量以便清楚.例如,考虑这个而不是原始代码:

private GObject getCollidingObject(){
    int x = ball.getX();
    int y = ball.getY();
    if (getElementAt(x, y) != null) {
        return getElementAt(x, y);
    }
    if (getElementAt(x + BALL_RADIUS * 2, y) != null) {
        return getElementAt(x + BALL_RADIUS * 2, y);
    }
    if (getElementAt(x, y + BALL_RADIUS * 2) != null) {
        return getElementAt(x, y + BALL_RADIUS * 2);
    }
    if (getElementAt(x + BALL_RADIUS * 2, y + BALL_RADIUS * 2) != null) {
        return getElementAt(x + BALL_RADIUS * 2, y + BALL_RADIUS * 2);
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

(你可以做同样的x + BALL_RADIUS * 2y + BALL_RADIUS * 2也.)

您可能也会考虑这样的事情:

private GObject getCollidingObject(){
    int x = ball.getX();
    int y = ball.getY();
    return getFirstNonNull(getElementAt(x, y),
        getElementAt(x + BALL_RADIUS * 2, y),
        getElementAt(x, y + BALL_RADIUS * 2),
        getElementAt(x + BALL_RADIUS * 2, y + BALL_RADIUS * 2));
}

private static getFirstNonNull(GObject... objects) {
    for (GObject x : objects) {
        if (x != null) {
            return x;
        }
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

(在C#中,使用null合并运算符有一种更好的方法,但不要介意......)