List reports all objects within as being the same java?

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?

Answers


I looked through your uploaded code and found the error.

You declared every field in the class Area as static:

public class Area {
    public static int posx;
    public static int posy;
    public static int posz;
}

The fields are therefore equals for all instances, because there is just one posx field for the class Area (read this question and the answers for details). Because of this every write to, e. g., posx overrides the old value. Remove the static keyword and then all instances of the class Area have 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 static variables. You should revisit this.


It's not the solution but you should begin your loop with i=0


You can try printing out hashcode() of each object to see if they are really the same, provided that is not overridden.

Also you are starting your iteration at 1, you need to start at 0 to iterate over the entire collection.


Are you sure you want to start with i=1 instead of i = 0? This might be relevant if you are running your tests with only two objects


Need Your Help

Reactive Extension (Rx) tutorial that is up to date

c# .net system.reactive

I am quite interested in Reactive Extensions but I cannot find an up to date tutorial. I started with Curing the asynchronous blues with the Reactive Extensions for .NET but it is out of date. I can

Bower not copying files in project folder

node.js twitter npm

I tried Twitter's new bower tool today, but unfortunately I couldn't get it to work as advertised. I'm using Ubuntu and have installed the latest node.js. I installed Node following the guide on no...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.