public class ArrayTssst {public static void main(String[] args){// int[] a = new int[]{1,15,3};/*int[] b = a;System.out.println(b[1]);*//* int[] b = new int[3];System.arraycopy(a, 0, b, 0, a.length); b[1] =55;for(int i=0;i<a.length;i++){System.out.println(a[i]);}*/Poin[] p1 = new Poin[]{new Poin(1,1),new Poin(2,2),new Poin(3,3)};Poin[] p2 = new Poin[3];/*System.arraycopy(p1, 0, p2, 0, p1.length);p2[2].x = 44;p2[2].y = 33;for(int i=0;i<p1.length;i++){System.out.println(p1[i]);}*/p2 = p1.clone();p2[2].x = 44;p2[2].y = 33;for(int i=0;i<p1.length;i++){System.out.println(p1[i]);}}}class Poin implements Cloneable{int x;int y;Poin(int x,int y){this.x = x;this.y = y;}public String toString(){return "x = "+x+", y = "+y;}public Object clone(){Object o=null;try {o = super.clone();} catch (CloneNotSupportedException e) {// TODO Auto-generated catch blocke.printStackTrace();}return o;}}
2 回答

搖曳的薔薇
TA貢獻1793條經驗 獲得超6個贊
克隆分為淺克隆和深克隆,如果直接使用繼承Object的克隆,則為淺克隆。
你想達到的效果是深克隆,如果你想實現深克隆,則需要重寫clone方法
打個比方來講深克隆和淺克隆。就用一筐蘋果來講,深克隆就是我們復雜了一筐蘋果(一個筐和筐里的蘋果),而淺克隆則只是復雜了一個筐,蘋果則不能直接的反應在筐里。這個列子不是很恰當,不過你可以這么去理解深克隆和淺克隆。

慕碼人8056858
TA貢獻1803條經驗 獲得超6個贊
對于數組這樣的集合,如果要克隆的話,需要遍歷里面的元素逐一克隆,這個是深克隆。還有一個方法就是用ObjectOutputStream 和ObjectInputStream也可以用來進行深克隆。
添加回答
舉報
0/150
提交
取消