avatar

浅拷贝与深拷贝

浅拷贝

浅拷贝只复制指向某个对象的指针,而不复制对象本身,新旧对象共享同一块内存

代码展示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.ArrayList;

public class ShallowCopyAndDeepCopyTest {

public static class User {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

public static void main(String[] args) {

User user = new User();

user.setName("123");

ArrayList<User> users1 = new ArrayList<>(),
users2 = new ArrayList<>();

users1.add(user);

users2.add(user);

System.out.println("user1的0索引位置的对象中的name为: " + users1.get(0).getName());
System.out.println("user2的0索引位置的对象中的name为: " + users2.get(0).getName());

users1.get(0).setName("456");

System.out.println("user1的0索引位置的对象中的name为: " + users1.get(0).getName());
System.out.println("user2的0索引位置的对象中的name为: " + users2.get(0).getName());

}
}

打印展示

浅拷贝

深拷贝

深拷贝会另外创造一个一模一样的对象,新对象跟原对象不共享内存,修改新对象不会改到原对象

代码展示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.util.ArrayList;

public class ShallowCopyAndDeepCopyTest {

/**
* Cloneable: 实现了该接口后,可以重写Object类中的clone方法,而不抛出CloneNotSupportedException异常
*/
public static class User implements Cloneable {

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

/**
* 克隆对象
*/
public Object clone() throws CloneNotSupportedException {
return super.clone();
}

@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}

public static void main(String[] args) throws CloneNotSupportedException {

User user1 = new User();

user1.setName("123");

/* 拷贝对象 */
User user2 = (User)user1.clone();

/* 创建新对象 */
User user3 = new User();

user3.setName("123");

ArrayList<User> users1 = new ArrayList<>(),
users2 = new ArrayList<>(),
users3 = new ArrayList<>();

users1.add(user1);
users2.add(user2);
users3.add(user3);

users1.get(0).setName("456");

System.out.println("user1的0索引位置的对象中的name为: " + users1.get(0).getName());
System.out.println("user2的0索引位置的对象中的name为: " + users2.get(0).getName());
System.out.println("user3的0索引位置的对象中的name为: " + users3.get(0).getName());

}
}

打印展示

深拷贝

文章作者: 123
文章链接: https://gao5805123.github.io/123/2021/05/13/%E6%B5%85%E6%8B%B7%E8%B4%9D%E4%B8%8E%E6%B7%B1%E6%8B%B7%E8%B4%9D/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 123
打赏
  • 微信
    微信
  • 支付宝
    支付宝