例子

2011-12-06 25 views
0
// shallow copy example 
public class a 
{ 
    public static void main(String[] args) throws CloneNotSupportedException 
    { 
     b x = new b(2); 
     System.out.println(x.i[0]); // previous value for object x 
     System.out.println(x.k); 
     b y =(b)x.clone(); // y shallow clone of object x 
     y.i[0] = 10; y.k = 999; // changed values in object y 
     System.out.println(y.i[0]); // values of y after change 
     System.out.println(y.k); 

     System.out.println(x.i[0]); // values of x after change  
     System.out.println(x.k); 
     System.out.println(x.getClass() == y.getClass()); // both objects belong to same class 
     System.out.println(x == y); // both objects are different, they are not the same 
    } 
} 

class b implements Cloneable 
{ 
    public int i[] = new int[1]; 
    int k; 

    public Object clone() throws CloneNotSupportedException 
    { 
     return super.clone(); 
    } 

    b(int j) 
    { 
     super(); 
     i[0] = j; 
     k = j + 2; 
    } 
} 

/*output 

2 
4 
10 
999 
10 
4 
true 
false 
*/ 
//********************************************************************* 
//deep copy example 

public class a 
{  
    public static void main(String[] args) throws CloneNotSupportedException 
    { 
     b x = new b(2); 
     System.out.println(x.i[0]); // object x values before change 
     System.out.println(x.k); 

     b y = (b)x.clone(); // deep clone y of object x 

     System.out.println(y.i[0]); // values of object y 
     System.out.println(y.k); 

     System.out.println(x.i[0]); // values of object x after changing the values of the members in object y in clone method 
     System.out.println(x.k); 
     System.out.println(x.getClass() == y.getClass()); 
     System.out.println(x==y); 
    } 
} 

class b implements Cloneable 
{ 
    public int i[] = new int[1]; 
    int k; 

    public Object clone()throws CloneNotSupportedException 
    { 
     b t = new b(6); 
     return t; 
    } 

    b(int j) 
    { 
     i[0] = j; 
     k = j+2; 
    } 
} 

/* 

2 
4 
6 
8 
2 
4 
true 
false 
*/ 

我已經寫的例子,請看看我離開了anything.I不得不放棄把它演示,並希望它能夠爲possible.Do一樣簡單,讓我知道我能否讓它變得更簡單。 我已經提供引號,無論他們改變了值或對象被克隆。例子

+1

演示應該很漂亮;請始終縮進。 –

+0

ok lemme編輯.. – Nav

+0

可能更好張貼在http://codereview.stackexchange.com –

回答

2

演示的黃金提示:使用有意義的類名稱和變量名稱,並使示例更加具體。使用例如Book類和Author

public class Book{ 
    private String title; 
    private Author author; 
... 
} 
public class Author{ 
    private String name; 
    ... 
} 

與getter/setter方法(或公共領域偶數),你可以做一個Book實例的深/淺克隆,並說明當您更改名稱有什麼變化的Author。與你所做的完全一樣,但更容易告訴觀衆,並且讓觀衆更容易遵循,因爲每個人都知道書籍和作者是什麼,並且不需要看代碼以遵循您的解釋

+0

謝謝我從你提到的一個想法..... ....但使用字符串是不好的淺拷貝的例子,因爲它會將它複製爲另一個對象認爲它是引用類型,因爲字符串是不可變的,所以不得不訴諸此..大聲笑 – Nav

+0

因此,我說你使用'作者'指代。如果您更喜歡使用int的話,您可以隨時將標題更改爲「int ISBNNumber」。只要你的觀衆可以理解 – Robin

+0

是啊:)與你同意...謝謝你的時間:) – Nav