简体   繁体   English

Java 是创建对象的深层副本还是仅链接到其引用

[英]Does Java creates a deep copy of the object or just link to its reference

Let say I have the following code:假设我有以下代码:

ArrayList<String> aList = new ArrayList<String>();
aList.add(new String("abc");
...
String aString = aList.get(0);

Does aString have a deep copy of aList.get(0), which means a new memory location with the new String object, or aString is just assigned a reference pointer to the same object as aList has in position 0? aString 是否有 aList.get(0) 的深层副本,这意味着新的 String 对象的新内存位置,或者 aString 只是分配了一个引用指针,指向与 aList 在位置 0 相同的对象?

没有隐式的深拷贝,引用被赋值。

aString holds a reference to the object created by the expression new String("abc") . aString保存对由表达式new String("abc")创建的对象的引用。 It does not hold a reference to the first position of the list, so changing the list after the assignment does not change aString .它不保存对列表第一个位置的引用,因此在赋值后更改列表不会更改aString Also, in Java, Strings are immutable objects, which means the value of the String itself cannot be changed.此外,在 Java 中,字符串是不可变对象,这意味着字符串本身的值不能改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM