6

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;

4 Answers 4

12

You would have replace:

return list;

with:

return new ArrayList<Integer>(list);

Otherwise the client can do...

foo.getList().add(5);

breaking encapsulation.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1

You can use the copy constructor

return new ArrayList<Integer>(list);

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.