Reputation: 311
This is regarding the usage of ArrayList returned by another class instance variable.
Class A {
//assigned list of string to it.
private List < String > newAl;
//returns the list
public List < String > getList() {
return newA1;
}
}
Class Test {
public void go() {
List < String > list = a.getList();
list.add("");
}
}
In the Test class when i retreive list and manipulate the list.Because of the reference ,class A list also got manipulated.If A is part of third party code.How do I correct my code in Test class so that original object wouldnt be affected?
Upvotes: 2
Views: 402
Reputation: 12239
The ArrayList constructor takes a Collection so you can use that:
List<String> list = new ArrayList(a.getList());
I think it's better to do it like this, but depending on what you're doing, you may want to construct the new List in the getter. That also helps type hiding.
Upvotes: 2