Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep copy when Using ArrayList in java

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

like image 352
user2735714 Avatar asked Feb 21 '15 12:02

user2735714


People also ask

Is ArrayList clone a deep copy?

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.

Is ArrayList constructor deep copy?

According to the result, it seems that the copy constructor is deep copy, not shallow copy.

How do you clone an ArrayList?

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.

Does ArrayList implements serializable?

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.


1 Answers

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.

like image 68
aioobe Avatar answered Oct 05 '22 11:10

aioobe