When to use clone() and how actually addAll() and add() works

孤者浪人 提交于 2019-12-06 07:01:50

Yes, addAll adds all the references of the source List to the target List. It doesn't create copies of the instances these references refer to.

This is sufficient when the List holds references to immutable objects. If you add or remove elements from one of the Lists after the addAll operation, the changes won't be reflected in the other List.

If the List holds references to mutable objects, and you are modifying the state of those objects, you must create copies (either using clone or a copy constructor) if you don't want changes in one List to be reflected in the other List.

BTW, passing a List to add (instead of to addAll) will add a reference of the List to the target List. Unless the target List is a List of Lists, you shouldn't do that. add should accept a single element to be added to the List.

It sounds like you want to add a copy of the objects of one list to another list. As Eran said, simply calling add() or addAll() isn't going to be enough, since this copies references.

To add to Eran's answer - it sounds like you think calling clone() is going to solve your problem, but that's only true if you've implemented a custom clone function! The default clone() only creates a shallow copy, meaning that any references contained in the cloned object are copied over.

Generally speaking, I find copy constructors or factory methods much easier and safer than clone().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!