《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.
在以上例子中, 当程序复制了数组后, 程序就修改了第二个数组的第三个元素. 当程序再显示两个数组的内容时, 可以发现, 所有两个数组都已被改变. 很明显,两个数组是指着同一个对象表.
相关文章推荐
- 《Java 编程技巧1001条》 第399条:对原始类型数组使用数组复制
- 《Java 编程技巧1001条》第401条:数组中存不同对象
- 《Java 编程技巧1001条》 第388条: 遍历多维数组
- 《Java 编程技巧1001条》 第395与396条 :了解和使用冒泡排序
- 《Java 编程技巧1001条》 第386条: 声明多维数组
- 《Java 编程技巧1001条》 第397+398条:了解和使用快速排序
- 《Java 编程技巧1001条》第391条: 在数组中查找一指定值
- 《Java 编程技巧1001条》 第408条: 使用mouseMove方法,
- 《Java 编程技巧1001条》第409...条: 使用crickCount方法,
- 《Java 编程技巧1001条》 第420...条: 使用handle event 方法
- 《Java 编程技巧1001条》 第384条: 建立对象数组..
- 《Java 编程技巧1001条》 第389条: 了解不平衡数组
- 《Java 编程技巧1001条》第416条:使用keyUp方法
- 《Java 编程技巧1001条》 第406条: 使用mouseUp方法
- 《Java 编程技巧1001条》 第394条: 数组分类(排序)
- 《Java 编程技巧1001条》 第387条: 建立多维数组
- 《Java 编程技巧1001条》第413条:使用mouseEnter 和 mouseExit
- 《Java 编程技巧1001条》 第382+283条: 了解数组的长度和引用
- 《Java 编程技巧1001条》 第405条: 使用mouseDoun方法
- 《Java 编程技巧1001条》 第393条: 使用2分查找