克隆字符串数组,使用java数组上的clone()方法。克隆后,我期望在新数组中包含新字符串 - 并为它们分配新地址。但是...我的行为有点不同,请看一下:
(它将打印:
same address
One
)
public class ArrayCopyClone {
static String[] array2 = new String[] {"One", "Two", "Three"};
public static void main(String[] args) {
String[] copy2 = array2.clone();
if (copy2[0] != array2[0]) {
System.out.println("good"); // will never show up
} else {
System.out.println("same address"); // I'm expecting never be here
}
array2[0] = "new";
System.out.println(copy2[0]); // "One", and this is OK (it means we have a copy)
}
}
与字符串阴影有关吗?应该是吗?
最佳答案
克隆数组会产生浅拷贝。所以内容是一样的。对于深度克隆,请参阅 here .
关于java - 克隆字符串数组,检查引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14836539/