Okay, so I have an arraylist of a custom class I made. Everytime i try to set the variable of one of the classes to something, all the object's variables in the arraylist change to that as well. Can anyone help?
Printable View
Okay, so I have an arraylist of a custom class I made. Everytime i try to set the variable of one of the classes to something, all the object's variables in the arraylist change to that as well. Can anyone help?
well, are you creating new instances of the object for each adding to the list.
for example,
this will create a list with three references to the same object instance, which when changing a property in one index, will of course appear to change all indicies in the array.Code:MyObject myObj = new MyObject();
List<MyObject> aList = new ArrayList<MyObj>();
aList.add(myObj);
aList.add(myObj);
aList.add(myObj);
Instead,
would create three different object references into the list.Code:List<MyObject> aList = new ArrayList<MyObj>();
aList.add(new MyObject());
aList.add(new MyObject());
aList.add(new MyObject());
Java uses pass by reference. When you add an object to an ArrayList, it does not create a new copy. Instead, it simply records the reference to that Object. Since there is only 1 object involved, when you change it, it changes in the ArrayList too...since it''s the same object. If you want an independent copy for your ArrayList, you'll need to create another one. I suggest looking at the 'clone' method of the Object class.
ray = new RayTest(level, new Vector(0, 0), new Vector(600, 600));
ray.setPosition(Vector.Zero);
list.add(ray);
int max = 1;
for (int i = 0; i < max * 65; i += 65)
{
list.add(new CircleTest(level, new Vector(i, -100)));
//System.out.println( ((CircleTest)list.get(i / 65)).getPosition() );
}
Here's a sample of my code. As you can see I use the new operator for each object that is added to the list, but I'm still getting the same problem.
You'll want to create and post a small program that is self-contained, compilable, and that we can run without modification and that demonstrates your error.
If you do post code, please be sure to use code tags so that your code retains formatting and is readable. To do this, simply surround your code with the tags:
[code]
and
[/code]
Suerte!