How to set an element in an array as a method parameter?

47 Views Asked by At

I've an array that consists of many objects (called drops) and another separate object (called greenDrop). I would like to compare 2 objects at one time, one from the array & the other will be the separate object. To set an array and a separate object as method parameters, code as follows:

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

I was wondering if it is possible to set an element of the array in the method parameter instead of using the entire array? This is so that I won't have to include the for loop in my method. Calling the method in the main method will then be as follows:

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

There are 2 best solutions below

1
Thiyagu On BEST ANSWER

The second parameter of the method can be changed as just Drop

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

But if you still want to use collision passing an array of Drop (from elsewhere), then you can use varargs

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

You can pass zero, one element or multiple (Drop) objects like

collision(greenDrop)

collision(greenDrop, drops[i])

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

I don't know from where numDrops is obtained. You might need to change that to gd2.length

0
Ridcully On

You can add a method to your GreenDrop class to check if it collides with a Drop. Or, if GreenDrop is derived from Drop you can put the method into the Drop class.

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

Then you can iterate your array of drops like so:

for(Drop drop : arrayOfDrops) {
    if (greenDrop.collides(drop)) {
        // collision detected
        // use break to exit for loop here if you want
    }
}