6

I know that it is a trivial matter but I want to ask this question. Suppose that I have a get method that returns an ArrayList of objects. First do we have to returns a copy of it? If so, does it have to be a deep copy of the ArrayList? Do we still need to do a deep copy when the objects inside it are immutable? If we use this type of constructor

ArrayList<T> arr = new ArrayList<>(collection);

then are the elements of the array copied or they still point to the old values? Thanks

0

1 Answer 1

5

It depends on your use case. Sometimes it's desirable to expose the underlying collection, some times it's not.

If you for instance want to leverage the collection methods for your class you could return the underlying collection (or a modifiable view of the underlying collection). This enables clients of your class to do, for instance

phoneBook.getPeople().removeIf(Person::isAddressInvalid);

If you don't want to expose the underlying collection I would go with

return new ArrayList<>(yourCollection);

I think it's very rare to return a deep copy in a get method.

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

2 Comments

Ok what if the type is String then can I return it this way: return new ArrayList<>(yourCollection);
Absolutely. Strings are immutable, so returning a deep copy of strings is particularly pointless.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.