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
ArrayList. clone() method is used to create a shallow copy of an ArrayList instance. We can also use this method to perform a deep copy of an ArrayList. In this post, we will learn how to use clone() method with different examples.
According to the result, it seems that the copy constructor is deep copy, not shallow copy.
Using a Copy Constructor: Using the ArrayList constructor in Java, a new list can be initialized with the elements from another collection. Syntax: ArrayList cloned = new ArrayList(collection c); where c is the collection containing elements to be added to this list.
In Java, the ArrayList class implements a Serializable interface by default i.e., ArrayList is by default serialized. We can just use the ObjectOutputStream directly to serialize it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With