測試陣列的 clone() 效果
我以為每個陣列都能用 clone(),但不然。
/** * * Title: * Description: 測試陣列的 clone() * Copyright: Copyright (c) 2005 * Company: Dark Dungeons * @author Fin * @version v0.01.01 */ public class TestArrayCopy { public TestArrayCopy() { }
/** * TestClass[].clone() 沒有作用。
*/ private void test1() { TestClass[] tc1 = new TestClass[10]; for (int i = 0; i < tc1.length; i++) { tc1 = new TestClass(); tc1.count = i; }
TestClass[] tc2 = (TestClass[]) tc1.clone(); System.out.println(tc2[0].count); tc1[0].count = 2; System.out.println(tc2[0].count); }
/** * String[].clone() 是有用的。
*/ private void test2() { String[] tc1 = new String[10]; for (int i = 0; i < tc1.length; i++) { tc1 = new String(); tc1 = String.valueOf(i); }
String[] tc2 = (String[]) tc1.clone(); System.out.println(tc2[0]); tc1[0] = "2"; System.out.println(tc2[0]); }
/** * int[].clone() 是有用的。
*/ private void test3() { int[] tc1 = new int[10]; for (int i = 0; i < tc1.length; i++) { tc1 = i; }
int[] tc2 = (int[]) tc1.clone(); System.out.println(tc2[0]); tc1[0] = 2; System.out.println(tc2[0]); }
public static void main(String[] args) { TestArrayCopy test = new TestArrayCopy(); test.test3(); }
class TestClass { int count = 0; }
}
|
|