您的位置:首页 > 编程语言 > Java开发

《Java 编程技巧1001条》 第400条: 使用数组复制

2017-12-23 10:51 555 查看



《Java 编程技巧1001条》第10章 用数组存储数据 第400条 在对象数组上使用数组复制

400 Using arraycopy on an Array of Objects
400 对Object数组使用数组COPY

You learnedin the previous tip that when you copy an array of primitives, the copy isphysically different from the original. However, Wwhen you copy an array ofobjects, only the object references are copied to the new array. The objectsthat make up the elements of the source array are not duplicated. When youmodify an object that is an element of one array, you actually modify thecorresponding element of the other array. Figure 400 illustrates how tovisualize an arraycopy of objects.
你在前面的TIP中已知道,当你COPY一个原始数组时, COPY是与原始的实际上不同的. 但是,当你COPY一个对象数组时,只有对象的引用被复制到新的数组中. 组成原有数组元素的对象是不复制的. 当你修改一个数组元素对象时,你实际是修改了另一数组的对应元素. 图400说明了怎样把对象的数组COPY弄的更直观化.Production: Place figure - arraycopy objects - SGFigure 400 Copying an array of objects.图400 对象数组的COPY
 
Thefollowing code demonstrates how to copy an array of objects:
以下程序说明怎样复制一个对象数组:public class arrayCopyObject {  public static void main(String[] args)    {     StringBuffer array1[] = new StringBuffer[5];     StringBuffer array2[] = new StringBuffer[5];      for (int i=0; i<array1.length; i++)       array1[i] = new StringBuffer(Integer.toString(i));      System.arraycopy(array1, 0, array2, 0, array1.length);      array2[2].append("00"); // modify second array      System.out.print("Array 1: ");      for (int i=0; i<array1.length; i++)       System.out.print(array1[i] + " ");      System.out.println();     System.out.print("Array 2: ");      for (int i=0; i<array2.length; i++)        System.out.print(array2[i] + " ");      System.out.println();    }  }
When you compile andexecute this program, your screen will display the following output.
当你你编译和执行这一程序时,你的屏幕上将出现以下的输出结果:Array 1: 0 1 200 3 4 Array 2: 0 1 200 3 4
In theprevious example, after the program copies the array, the program modifies thethird element of the second array. After the program displays the contents ofboth arrays, notice that the both arrays have been modified. Clearly, botharrays point to the same list of objects.
在以上例子中, 当程序复制了数组后, 程序就修改了第二个数组的第三个元素. 当程序再显示两个数组的内容时, 可以发现, 所有两个数组都已被改变. 很明显,两个数组是指着同一个对象表.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: