Reputation: 374
Asking for java help
I am 1.5 weeks into programming so try and make an answer easy for an idoit. And this answer is probably out there and I am probably to dumb to realize I read it already.
So I have a bunch of object instances and I want to add Instance.position which is
double[] position = (x,y);
to some sort of array/list/stack so I can the check to see if a different object Instance.position is the same as one I set to the array/stack/list.
This is what i have:
public ArrayList<double[]> objPositions = new ArrayList<double[]>();
public boolean isThereAObj(double[] userPosition){
if (objPositions.contains(userPosition));
return true;
}
this does not work.. (i think)
where the array list has already been defined earlier and ideally my array list could be of objects and i could check the objects element position with my comparing objects position.
So basically I want to have a list with all instances of all objects I create in my program and then I want to be able to compare one or more of their elements to a different object (not on the list)
Upvotes: 1
Views: 27606
Reputation: 54659
There are several issues here. First, it is not very elegant to describe a 2D point as a 2-element double[]
array. Instead, you should consider using java.awt.geom.Point2D
objects:
Point2D p = new Point2D.Double(x,y);
This makes the implementation of the method that you are looking for much easier:
private final List<Point2D> wallPositions = new ArrayList<Point2D>();
public boolean isThereAWall(Point2D userPosition) {
return wallPositions.contains(userPosition);
}
The problem with your current attempt is that double[]
arrays do not know the concept of "equality" that you are looking for. (More formally: There is no appropriate implementation of the Object#equals(Object)
method for them)
However, if you want to stick to your double arrays (although I do not recommend this), you could do something like
private final List<double[]> wallPositions = new ArrayList<double[]>();
public boolean isThereAWall(double[] userPosition) {
for (double entry[] : wallPositions) {
if (Arrays.equal(entry, userPosition)) {
return true;
}
}
return false;
}
But there may (in both cases) be another caveat, namely the limited precision of double
values. There are very few cases where it is appropriate to compare double
values for identity (with ==
). But whether this really is a problem here depends on your application case.
Upvotes: 8
Reputation: 8825
Use Point2D.Double
, which is exactly meant to store 2 double
s in a Point
object. You can keep multiple points in an ArrayList
, as you are now. To check whether a point already exists, you'd just loop through it and call .equals(newPoint)
to compare the points. However, as double
precision points might not ever equal each other, you probably want to check whether two points are within a certain small distance from each other (again, with equals()
for example).
Upvotes: 1