Reputation: 11
I would like to ask how do we find the element in an array with the value of a variable inside the element? Is it possible? If so, please do tell. Suppose we have an object called Pt:
public class Pt {
private int x, y;
public void setCoords(int i, int j){
x = i;
y = j;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}
Then we create an Array of Pt object and also initialize it's elements.
Pt[] point;
point[0].setCoords(0,0);
point[1].setCoords(1,1);
The problem that I am having now is how do I find the element with the coordinates (1,1)?
Upvotes: 0
Views: 82
Reputation: 149
public static void main(String[] args) {
Pt[] point = new Pt[2];
Pt pt1 = new Pt();
pt1.setCoords(0, 0);
Pt pt2 = new Pt();
pt2.setCoords(1, 1);
point[0] = pt1;
point[1] = pt2;
getElement(point, 1, 1); // returns element with coords of (1, 1) or null if doesn't exist
}
public static Pt getElement(Pt[] point, int xCoord, int yCoord) {
for (int i = 0; i < point.length; i++) {
if (point[i].getX() == xCoord && point[i].getY() == yCoord) {
return point[i];
}
}
return null;
}
Upvotes: 0
Reputation: 271625
You just need to loop through the array and check each of the elements. To loop through the array, you can use an enhanced for loop.
for (Pt pt : point) {
if(pt.getX() == 1 && pt.getY() == 1){
//what you want to do with the object...
break;
}
}
Upvotes: 1