一个引用对象问题

大概是这样的一个故事,首先看成员: 谢霆锋,张柏芝 以及他的两个儿子,如果实体没有实现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);
    }
原文地址:https://www.cnblogs.com/LIANQQ/p/3937612.html