0

我有一个由许多对象(称为 drop)和另一个单独的对象(称为 greenDrop)组成的数组。我想一次比较 2 个对象,一个来自数组,另一个是单独的对象。要将数组和单独的对象设置为方法参数,代码如下:

public boolean collision (GreenDrop gd1, Drop [] gd2){
    for(int i=0;i<numDrops;i++)
    {
        int xDistBetwnDrops=gd1.xpos-gd2[i].xpos;
        int yDistBetwnDrops=gd1.ypos-gd2[i].ypos;
        int totalLengthOfDrops=(gd1.xpos+gd1.size)+(gd2[i].xpos+gd2[i].size);
        if(xDistBetwnDrops<(totalLengthOfDrops/2)&&yDistBetwnDrops<(totalLengthOfDrops/2))
        {
            return true;
        }
    }
    return false;
}

我想知道是否可以在方法参数中设置数组的元素而不是使用整个数组?这样我就不必在我的方法中包含 for 循环。然后在main方法中调用方法如下:

if(collision(greenDrop, drops[i])==true)
4

2 回答 2

0

该方法的第二个参数可以更改为Drop

public boolean collision (GreenDrop gd1, Drop gd2){
    ...
    //The code has to be changed to not loop (Just compare two objects)
}

但是如果你仍然想使用collision传递一个数组Drop(来自其他地方),那么你可以使用varargs

public boolean collision (GreenDrop gd1, Drop... gd2){
    ...
}

您可以传递零个、一个元素或多个 (Drop) 对象,例如

collision(greenDrop)

collision(greenDrop, drops[i])

collision(greenDrop, drops[i], drops[j])

不知道从哪里numDrops得到。您可能需要将其更改为gd2.length

于 2018-10-13T05:16:28.597 回答
0

您可以向 GreenDrop 类添加一个方法来检查它是否与 Drop 碰撞。或者,如果 GreenDrop 是从 Drop 派生的,您可以将该方法放入 Drop 类中。

class GreenDrop {
...
    public boolean collides(Drop drop) {
        int xDistBetwnDrops=this.xpos-drop.xpos;
        ...
    }
}

然后你可以像这样迭代你的drop数组:

for(Drop drop : arrayOfDrops) {
    if (greenDrop.collides(drop)) {
        // collision detected
        // use break to exit for loop here if you want
    }
}
于 2018-10-13T05:32:20.643 回答