After adding the object into my list I am changing the data in the list it is getting modified I have the code like
List<Data> oldList = // initializing the list
List<Data> newList = // initializing the list
for (Data data: oldList) {
if (condition) {
data.setvalue("");
newList.add(data);
data.setAnother();
}
}
If I am doing like this, the data object in the newList
also is getting changed.
I have a requirement that it should be changed in the oldList
but it should not change the data in the newList
.
Advertisement
Answer
If you don’t want the objects in the newList
get affected while changing the object from the oldList
, then need to create a copy of each object that should be added to the newList
.
For that, you can implement a copy-constructor (a constructor that expects an object of the same type as an argument) in the Data
class or make it implement Clonable
interface (but this approach has some serious pitfalls see here – paragraph “Copy Constructor versus Cloning”).
Assuming that you’ve implemented a copy-constructor, your code might be written like this:
List<Data> oldList = // initializing the list
List<Data> newList = // initializing the list
for (Data data: oldList) {
if (condition) {
Data copyForNewList = new Data(data); // creating a copy of the data object
copyForNewList.setvalue(""); // changing the copy
newList.add(copyForNewList); // string the copy
data.setAnother(); // mutating the original object
}
}