Akshay
Akshay

Reputation: 13

java list cannot add class then alter original class without altering the copy from the list

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.

Upvotes: 1

Views: 194

Answers (2)

Greg Hewgill
Greg Hewgill

Reputation: 993611

In Java, objects references act like pointers in C++. There is no notion of "copy constructor". You have noticed this when you've added something to a list and then change the item after adding it to a list.

Generally in Java you will use new to create a new Item every time you add a new one to the list. So something like:

while (...) {
    Item i = new Item(...);
    stuff.add(i);
}

rather than

Item i = new Item();
while (...) {
    i.foo = ...;
    stuff.add(i);
}

The second example above will add the same object to the list multiple times.

Upvotes: 1

Greg Kopff
Greg Kopff

Reputation: 16595

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 Cloneable and override the clone() method. If you have only primitives in Item, then you can simply do:

public Object clone()
{
  return super.clone();
}

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():

By convention, the object returned by this method should be independent of this object (which is being cloned). To achieve this independence, it may be necessary to modify one or more fields of the object returned by super.clone before returning it. Typically, this means copying any mutable objects that comprise the internal "deep structure" of the object being cloned and replacing the references to these objects with references to the copies. If a class contains only primitive fields or references to immutable objects, then it is usually the case that no fields in the object returned by super.clone need to be modified.

Upvotes: 1

Related Questions