---
title: "Java的深拷贝和浅拷贝--等号赋值（一）"
author: "tessykandy"
date: "2013-05-02T17:31:24Z"
tags: ["Java", "拷贝", "深拷贝"]
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2013-05-02T17:32:45Z"
id: 1858844
url: "https://tessykandy.iteye.com/blog/1858844"
---

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

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

![](http://dl.iteye.com/upload/attachment/0083/9490/4bed86fe-4dda-33ee-b0de-0e0fb4cf8ac9.png)  
 （一）预定义非集合类型等号(=)赋值 

```
	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 

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