sevenxuguang
sevenxuguang

Reputation: 177

Encapsulation for mutable objects in Java

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;

Upvotes: 6

Views: 1265

Answers (4)

Pace
Pace

Reputation: 43817

You would have replace:

return list;

with:

return new ArrayList<Integer>(list);

Otherwise the client can do...

foo.getList().add(5);

breaking encapsulation.

Upvotes: 12

markspace
markspace

Reputation: 11030

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.

Upvotes: 2

Mandeep Rajpal
Mandeep Rajpal

Reputation: 1777

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);

Upvotes: 0

Untitled123
Untitled123

Reputation: 1293

You can use the copy constructor

return new ArrayList<Integer>(list);

Upvotes: 1

Related Questions