一個引用對象問題

來源:互聯網
上載者:User

標籤:style   blog   color   io   for   ar   問題   div   代碼   

大概是這樣的一個故事,首先看成員: 謝霆鋒,張柏芝 以及他的兩個兒子,如果實體沒有實現Cloneable方法,沒有調用clone方法,將會得到兩個不同的結果。

首先看結果:

錯誤的結果1:(未實現實體的Cloneable方法)

我是第一個孩子我的名字是Lucas我爸是謝霆鋒我媽是張柏芝我是第二個孩子我的名字是Quintus我爸是謝霆鋒我媽是張柏芝突然有一天,港媒記者爆料,第一個孩子的老爸是陳冠希Lucas的爸爸是謝霆鋒Quintus的爸爸是謝霆鋒

正確的結果2:(實現實體的Cloneable方法)

我是第一個孩子我的名字是Lucas我爸是謝霆鋒我媽是張柏芝我是第二個孩子我的名字是Quintus我爸是謝霆鋒我媽是張柏芝突然有一天,港媒記者爆料,第一個孩子的老爸是陳冠希Lucas的爸爸是陳冠希Quintus的爸爸是謝霆鋒

 

代碼實現

Coding :

 實體:

package com.example.model;public class Student implements Cloneable {  public String Name;  public String Father;  public String Monther;  @Override  protected Object clone() throws CloneNotSupportedException {    // TODO Auto-generated method stub    Student o = null;    try {      o = (Student) super.clone();    } catch (CloneNotSupportedException e) {      e.printStackTrace();    }    return o;  }}

Coding:

List<Student> AllList = new ArrayList<Student>();    Student Chirld = new Student();    Student Lucas = new Student();    Student Quintus = new Student();    Chirld.Father = "謝霆鋒";    Chirld.Monther = "張柏芝";    Quintus = Chirld;    Lucas = Chirld;    Lucas.Name = "Lucas";    Log.d("1", "我是第一個孩子" + "我的名字是" + Lucas.Name + "我爸是" + Lucas.Father + "我媽是" + Lucas.Monther);    Quintus.Name = "Quintus";    Log.d("2", "我是第二個孩子" + "我的名字是" + Quintus.Name + "我爸是" + Quintus.Father + "我媽是"        + Quintus.Monther);    Log.d("3", "突然有一天,港媒記者爆料,第一個孩子的老爸是陳冠希");    // 爆料過程    for (int i = 0; i < 2; i++) {      Student name = new Student();      name = Chirld;      if (i == 1)        name.Father = "謝霆鋒";      else        name.Father = "陳冠希";      AllList.add(name);    }    // 爆料完畢    Log.d("最後他們說", "");    for (int i = 0; i < AllList.size(); i++) {      String name = "";      if (i == 0) {        name = "Lucas";      } else {        name = "Quintus";      }      Student str = AllList.get(i);      Log.d("他們說", name + "的爸爸是" + str.Father);    }

 

主要錯誤在爆料過程的迴圈中,雖然new了兩個對象,但是指向的是同一塊記憶體地區。這時候必須調用Cloneable的clone方法,複製一個實體,才能真正將值改變

Coding

    // 爆料過程    for (int i = 0; i < 2; i++) {      Student name = new Student();      try {        name = (Student) Chirld.clone();      } catch (CloneNotSupportedException e) {        // TODO Auto-generated catch block        e.printStackTrace();      }      if (i == 1)        name.Father = "謝霆鋒";      else        name.Father = "陳冠希";      AllList.add(name);    }

 

一個引用對象問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.