【发布时间】:2013-01-27 23:52:37
【问题描述】:
克隆字符串数组,在 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)
}
}
它与字符串阴影有关吗?应该吗?
【问题讨论】:
-
你为什么在乎?字符串是不可变的;任何字符串和该字符串的任何副本之间都没有区别。