Im using a list of objects (Area) in java, which i defined as so:
public static List<Area> areaList = new ArrayList<Area>();
I add content to my list as so:
areaList.add(new Area(px, py, pz, radius, wl));
then i access the list, to check each of the Area’s within it like so:
for (int i = 1; i < areaList.size(); i++) {
System.out.println(areaList.get(i).somevariable));
}
(ignore the ‘somevariable’ and i also didnt use println(), this was for example, the way i accessed using:
areaList.get(i)
is whats important here)
But it returns all the objects inside the List as having the same values – that of the last one accessed.
Can anyone tell me where im going wrong?
I looked through your uploaded code and found the error.
You declared every field in the class
Areaas static:The fields are therefore equals for all instances, because there is just one
posxfield for the classArea(read this question and the answers for details). Because of this every write to, e. g.,posxoverrides the old value. Remove thestatickeyword and then all instances of the classAreahave their own instance variable.You should also think about making them private and provide getter and setter methods.
I haven’t looked in detail through your code, but there are several places where you used
staticvariables. You should revisit this.