Consider this code:
package Prova;
import java.util.ArrayList;
public class Prova
{
private ArrayList<String> people;
public Prova() {
people=new ArrayList<String> ();
}
public ArrayList<String> getPeople (){
return people;
}
public static void main(String[] args) {
Prova p=new Prova();
p.go();
}
public void go(){
ArrayList<String> temp=getPeople();
temp.add("jack");
System.out.print(getPeople());
}
}
It prints “jack”.
Why? Doesn’t this violate encapsulation? How to return it by value?
You need to program defensively. There are a few alternatives to consider
As far as the why goes, it’s as already explained by other posts. The value to the reference of the
ArrayListis passed (alas changing the value doesn’t change the original reference). However the list itself contains modifiable references to its objects.