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?

05-21-2010, 12:41 AM

travishein

well, are you creating new instances of the object for each adding to the list.

for example,

Code:

MyObject myObj = new MyObject();

List<MyObject> aList = new ArrayList<MyObj>();

aList.add(myObj);
aList.add(myObj);
aList.add(myObj);

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.

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.