简体   繁体   English

列表时会发生什么 <Integer> A =清单 <Integer> B?

[英]What happens when List<Integer> A = List<Integer> B?

What happens when I do this: 当我这样做时会发生什么:

List<Integer> listA = new ArrayList<Integer>();
List<Integer> ListB = new ArrayList<Integer>();

listA = ...filled with some data...
listB = ...filled with some other data...

listA.clear();
listA = listB;

Does values copies or just re-reference? 值会复制还是只是重新引用? If I now (after this code) call listA.clear() again , will listB clear as well? 如果我现在(在此代码之后listA.clear() 再次调用listA.clear()listB也将清除吗?

Well, after listA = listB the variable listA references the same list as listB . 好了,经过listA = listB变量listA引用相同的列表作为listB There is no copy-constructor in Java like you have it in C++ etc. Java中没有像C ++这样的复制构造函数。

只是引用的值将被复制,因此它们两个都将引用同一对象

Only primitive types are copied by value, if you do the above you'll have listA and listB referencing the same list, so whatever you do with listA will have the same effect on listB and vice-verse. 仅原始类型按值复制,如果执行上述操作,则listA和listB将引用同一列表,因此,对listA进行的任何操作都会对listB产生相同的影响,反之亦然。 and if you want to lose the reference just set one of the variables to null. 如果要丢失引用,只需将变量之一设置为null。

No, listA and listB are two different list of integers, They are not related to each other. 不, listAlistB是两个不同的整数列表,它们彼此不相关。 If you do a clear() on the ListA , ListB will not be affected at all. 如果在ListA上执行clear() ,则ListA ListB不会受到影响。 In your case at the end ListA reference is changed and the variable is now pointed to ListB . 在您的情况下,最后ListA引用已更改,并且变量现在指向ListB So, Both of these variables point to one List that is ListB . 因此,这两个变量都指向一个ListB So, any action on any of these references will have the same effects. 因此,对这些引用中的任何一个执行的任何操作都会产生相同的效果。 ListA object is already empty, it contains nothing. ListA对象已经为空,不包含任何内容。 and there is not any way to refer that object. 并且没有任何方法可以引用该对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM