Java中,对于基本类型,可以用“=”进行克隆,而对于引用类型却不能简单的使用“=”进行克隆,这与JAVA的内存使用空间有关,JAVA在栈中保存基本类型和引用变量,在堆中保存对象。对于引用变量而言,使用“=”将修改引用,而不是复制堆中的对象,此时两个引用对象将指向同一个对象,因此如果对一个变量修改则会修改另一个对象。
public class Employee { private String name; private int age; //省略get和set方法 @Override public String toString() { return "姓名:" + name + ", 年龄:" + age; } } public class Test { public static void main(String[] args) { System.out.println("克隆之前:"); Employee employee1 = new Employee(); employee1.setName("芋头1"); employee1.setAge(12); System.out.println("员工1的信息:"); System.out.println(employee1); System.out.println("克隆之后:"); Employee employee2 = employee1; employee2.setName("芋头2"); employee2.setAge(114); System.out.println("员工2的信息:"); System.out.println(employee2); System.out.println("员工1的信息:"); System.out.println(employee1); } }
public class Address { private String state; private String province; private String city; //省略get和set @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("国家:" + state + ", "); sb.append("省:" + province + ", "); sb.append("市:" + city); return sb.toString(); } } public class Employee implements Cloneable { private String name; private int age; private Address address; //省略get和set @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("姓名:" + name + ", "); sb.append("年龄:" + age + "\n"); sb.append("地址:" + address); return sb.toString(); } @Override public Employee clone() { Employee employee = null; try { employee = (Employee) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return employee; } } public class Test { public static void main(String[] args) { System.out.println("克隆之前:"); Address address = new Address("中国", "吉林", "长春"); Employee employee1 = new Employee("明日科技", 12, address); System.out.println("员工1的信息:"); System.out.println(employee1); System.out.println("克隆之后:"); Employee employee2 = employee1.clone(); employee2.getAddress().setState("中国"); employee2.getAddress().setProvince("四川"); employee2.getAddress().setCity("成都"); employee2.setName("西南交通大学"); employee2.setAge(114); System.out.println("员工2的信息:"); System.out.println(employee2); System.out.println("员工1的信息:"); System.out.println(employee1); } }输出:
在Adress类中增加
protected Address clone() { Address address = null; try { address = (Address) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return address; }
public Employee clone() { Employee employee = null; try { employee = (Employee) super.clone(); employee.address = address.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); }
原文地址:http://blog.csdn.net/chaoshenyutou/article/details/41848251