ITeye博客

Java的深拷贝和浅拷贝--等号赋值(一)

tessykandy · 2013-05-02 17:31 · JAVA · 编程语言 · Java · 拷贝 · 深拷贝 · Markdown

Java中常用的拷贝操作有三个,operator = 、拷贝构造函数 和 clone()方法。

不同的类型在拷贝过程中的表现:


 (一)预定义非集合类型等号(=)赋值 

	private void testEqualOperator() {
		int x = 1;
		int y = x;
		y = 2;
		if (x != y) {
			System.out.println("deep copy");
		}

		Integer a = 1;
		Integer b = a;
		b = 2;
		if (!a.equals(b)) {
			System.out.println("deep copy");
		}

		String m = "ok";
		String n = m;
		n = "no";
		if (!m.equals(n)) {
			System.out.println("deep copy");
		}
	}

 结果:都是deep copy  

 结论:预定义非集合类型等号(=)赋值 -- 深拷贝

 

2.预定义集合类型等号(=)赋值 

	private void testEqualOperator() {
		List<String> listStringsA = new ArrayList<String>();
		listStringsA.add("a");
		listStringsA.add("b");
		
		List<String> listStringsB = listStringsA;
		listStringsB.add("c");
		
		for (String str : listStringsA) {
			System.out.println(str);
		}
	}

 结果: 

a
b
c

 结论:预定义集合类型等号(=)赋值--“浅拷贝” 

 

3. 自定义类型等号赋值  

class Person {
	private int age;
	private String name;
	
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

public class AboutCopy {
	
	private void testEqualOperator() {
		Person a = new Person();
		a.setName("NameA");
		a.setAge(10);
		
		Person b = a;
		b.setAge(15);
		
		System.out.println(a.getAge());
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		AboutCopy testObj = new AboutCopy();
		testObj.testEqualOperator();

	}

}

 结果:15 

 结论: 自定义类型等号赋值 -- 浅拷贝

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。