问题描述
当您调用ArrayList的clone()方法时,将创建列表的浅表副本.什么是数组的浅表副本?
When you call the clone() method of an ArrayList, a shallow copy of the list is created.what is shallow copy of array?
推荐答案
您应该区分两种副本:浅和深.
You should distinguish between two kinds of copy: shallow and deep.
虽然深层副本会为整个数组及其所有内容分配新的空间(如果包含引用,则会分配新空间以创建具有与所复制实例相同的值的实例),而浅层副本只会分配具有相同大小的空间复制的数组.
While deep copy allocates new space for the whole array and all its content (if it contains references, then new space is allocated to create instances with the same values of the ones copied), shallow copy just allocates space with the same size of the copied array.
示例:
数组 A 已分配为仅包含两个可变对象(例如:列表或数组列表).您是否只想要一个"extern"数组的副本(包含两个引用的数组),还是想要一个深层副本,该副本将为包含在其中的两个引用的 also 新实例分配一个?
Array A has been allocated to contain only two mutable objects ( e.g.: a list or an arraylist).Do you want to have just a copy of the "extern" array (the one that contains the two references) or do you want a deep copy, that will allocate also new instances of the two references contained in A ?
在第一种情况下,例如:
In the first case, for example:
A是从参考0x0000AA开始的数组
A is the array starting at reference 0x0000AA
ElementOne从0x00BBCC开始
ElementOne starts at 0x00BBCC
ElementTwo从0x00BBFF开始
ElementTwo starts at 0x00BBFF
如果执行浅表副本:
B(新数组)将从参考0x0000BB开始,ElementsOne和ElementsTwo将指向旧引用(0x00BBCC,0x00BBFF).
B (the new array) will start at reference 0x0000BB,ElementsOne and ElementsTwo will point to the old references (0x00BBCC, 0x00BBFF).
如果执行深层复制,不仅会为数组分配新的空间,还会分配空间来包含新的实例(新列表,新arraylist ...).
If you execute a deep copy, not only it allocates the new space for the array, but it also allocates space to contain the new instances (a new list, a new arraylist ...).
这篇关于什么是数组的浅表副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!