问题
I was studying the "Java SE 7 Programmer I & II Study Guide" and I did not understand the explanation below.
class Fortress{
  private String name;
  private ArrayList<Integer> list;
  Fortress() {list=new ArrayList<Integer>;
  String getName{return name;}
  void addToList(int x){list.add(x);}
  ArrayList getList(){return list;} // line 1
}
Which lines of code break encapsulation? Answer: line 9. "When encapsulating a mutable object like an ArrayList, your getter must return a reference to a copy of the object, not just the reference to the original object".
I did not either understand the explanation or how to modifiy the original code.
So in the getList() instead of
return list;
Should we do this?
ArrayList<Integer> list2=list;
return list2;
    回答1:
You would have replace:
return list;
with:
return new ArrayList<Integer>(list);
Otherwise the client can do...
foo.getList().add(5);
breaking encapsulation.
回答2:
we do this?
ArrayList<Integer> list2=list;
return list2;
No, it says a copy of the object, not a copy of the reference.
ArrayList<Integer> list2= new ArrayList<>();
list2.addAll( list );
return list2;
Or as pointed out, ArrayList has a copy constructor that will add all elements from another list to the new list.  The above three lines are intended primarily to be clear what is being done.
回答3:
You can use the copy constructor
return new ArrayList<Integer>(list);
    回答4:
return list;
would return the reference to your private ArrayList list this is where the encapsulation breaks.
ArrayList<Integer> list2=list;
return list2;
Even here also you are simply passing the reference of your list to list2 You can try -
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.addAll(list);
    来源:https://stackoverflow.com/questions/34503190/encapsulation-for-mutable-objects-in-java