标签:style blog color io os ar java sp div
浅拷贝:java Ojbect类提供的clone只是拷贝本对象,其对象内部的数组和引用对象等都不拷贝,还是指向原生对象的内部元素地址。
类引用的成员变量必须满足两个条件才不会被拷贝:1.是类的成员变量而不是方法内变量;2必须是一个可变的引用对象,而不是一个原始类型或者不可变对象(包括int、long、char等及其对象类型[Integer、Long]、String)
测试代码:
import java.util.ArrayList; import java.util.List; public class Thing implements Cloneable{ String s = null; Integer i = null; private List<String> list = new ArrayList<String>(); public Thing(String s,int i) { System.out.println("init"); this.s = s; this.i = i; } public void setS(String s) { this.s = s; } public void println() { System.out.println( this.s + "\t" + this.i + "\t" + this.list.toString()); } public void setI(Integer i) { this.i = i; } public void setValue(String value) { this.list.add(value); } public Thing clone() { try { return (Thing) super.clone(); } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static void main(String[] args) { Thing t = new Thing("one",7); t.setValue("list1"); Thing clone = (Thing) t.clone(); t.setS("SECOND"); t.setI(10); t.setValue("list2"); System.out.print("t:"); t.println(); System.out.print("clone:"); clone.println(); } }
运行结果:
init t:SECOND 10 [list1, list2] clone:one 7 [list1, list2]
标签:style blog color io os ar java sp div
原文地址:http://www.cnblogs.com/visoncheng/p/4052411.html