I have a ArrayList collection 1 of Details type. I assign it to another collection 2 to perform manipulations on it so that it does not affect collection 1. But I see the collection 1 is affected since object is referenced. But I want to have a two different collection with different memory references - plz help me.
Details class -
public class Details implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private boolean enabled;
private int number;
public Details() {
}
public Details(int number, boolean enabled) {
this.enabled = enabled;
this.number = number;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public boolean getEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
Main class -
public static void main(String[] args) {
List<Details> detailsList = new ArrayList<Details>();
detailsList.add(new Details(10, false));
detailsList.add(new Details(20, false));
List<Details> newDetailsList = new ArrayList<Details>(detailsList);
for(Details d : newDetailsList) {
d.setEnabled(true);
d.setNumber(50);
}
for(Details d : detailsList) {
System.out.println("---" + d.getEnabled());
System.out.println("---" + d.getNumber());
}
}
Output -
---true
---50
---true
---50
I create a new collection newDetailsList
from detailsList
and modify it... I see the changes were applied to detailsList collection. How can I avoid that