So i mostly program in C++, and java is very similar to c++.
I have created a list command as such
List<Item> stuff =new ArrayList<Item>();
where Item is a custom class that basically stores data.
I get information from a text file and store it to Item.
Then i use stuff.add to get the item class to stuff.
Afterwards i use a command to erase all data from the item class and see that it has also deleted all the data from the list.
Basically I want to know if there is a way to add a copy of the class and not the address of the class itself.
Edit:
so i found that reinitializing the item class also solved my problem thanks though.
You want to clone the item before adding it to the list. The list just has a reference to the original item that you created. As such, when you mutate your item, the item in the list is also affected (it’s the same object).
If you want to “disconnect” the item that you put into your list, then you can clone it first. Your item class will need to implement
Cloneableand override theclone()method. If you have only primitives in Item, then you can simply do:If you have other objects in Item, then the default clone operation will only make a shallow copy, and you will need to make your clone method more extensive so that it makes deep copies. From the Javadoc for Object.clone():