何时使用 clone() 以及 addAll() 和 add() 的实际工作原理 [英] When to use clone() and how actually addAll() and add() works
问题描述
我在 MySQL 中使用 Java.
I am using Java with MySQL.
我的项目中有大约 60 个事务屏幕.我曾使用 add()
和 addAll()
函数来复制 ArrayList
.
There are about 60 transactions screens are there in my project. I had used add()
and addAll()
functions to copy an ArrayList
.
例如:
List<Bean> a1 = new ArrayList<Bean>(); // and add some value
List<Bean> a2 = new ArrayList<Bean>();
a2.addAll(a1);
在这种情况下:
- 在大多数屏幕中,
add()
或addAll()
函数没有任何问题,但对于某些屏幕,如果在列表a2
它也会影响a1
列表. - 在这些特定屏幕中,克隆概念(实现
Cloneable
接口)用于摆脱它并使其正常工作.
- In most of the screens, there is no any issue on
add()
oraddAll()
functions, but for some screens, if made change on lista2
it also affects thea1
list. - In these particular screens, clone concept (implements
Cloneable
interface) is used to get rid from it and its working fine.
根据我的研究,add()
函数只设置对目的地列表的引用.
According to my study, add()
functions sets only reference to destinations list.
我的疑问是:
- 为什么需要
clone()
(仅适用于某些情况而不适用于所有情况)? - 如果我们
add()
或addAll()
将一个列表放入另一个列表中,实际上会发生什么? clone()
是否对add()
或addAll()
方法是必需的?- 哪些地方应该使用
clone()
,哪些地方不应该使用? - 如果我们对列表
a2
进行了任何更改,列表a1
会发生什么?
- Why
clone()
is required (For some cases only and not in all)? - What happens actually if we
add()
oraddAll()
a list into another list? - Whether,
clone()
is mandatory foradd()
oraddAll()
methods or not? - Where we should use
clone()
and where shouldn't? - What should happen to list
a1
if we made any changes in lista2
?
我的最后一个问题:
何时使用 clone()
或复制构造函数以及何时不需要使用.在通用的 List
中,如果我们像上面的例子那样在目标列表中进行更改,源列表会发生什么.
When to use clone()
or copy constructor and when we need not to use.
And in generic List
, what should happen to source list if we made changes in target list like above example.
推荐答案
是的,addAll
将源 List 的所有引用添加到目标 List 中.它不会创建这些引用所引用的实例的副本.
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.
当 List 包含对不可变对象的引用时,这就足够了.如果您在 addAll
操作后从其中一个列表中添加或删除元素,则更改将不会反映在另一个列表中.
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.
如果 List 持有对可变对象的引用,并且您正在修改这些对象的状态,如果您不希望一个 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.
顺便说一句,将 List 传递给 add
(而不是 addAll
)会将 List 的引用添加到目标 List.除非目标 List 是 List of Lists,否则您不应该这样做.add
应该接受要添加到列表中的单个元素.
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.
这篇关于何时使用 clone() 以及 addAll() 和 add() 的实际工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!