ArrayList 保存引用是的。但是您可以克隆它(注意!但这将是浅拷贝 - 对于内部对象,它也不会克隆https://stackoverflow.com/a/13434779/1111527)
private class JustToCheck implements Cloneable {
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
然后像这样使用
JustToCheck ob1 = new JustToCheck();
JustToCheck ob2 = ob1;
List<JustToCheck> arr = new ArrayList<JustToCheck>();
arr.add(ob1);
arr.add(ob2);
System.out.println(arr.get(0).toString() + ": " + arr.get(1).toString());
try {
arr.set(1, (JustToCheck) ob1.clone());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
System.out.println(arr.get(0).toString() + ": " + arr.get(1).toString());
输出是
example$JustToCheck@1c39a2d: example$JustToCheck@1c39a2d
example$JustToCheck@1c39a2d: example$JustToCheck@bf2d5e
PS - 我已经检查了答案中的问题https://stackoverflow.com/a/13434813/1111527
有不可变类的东西
Java6
String a = new String("a");
String b = a;
b += "b";
System.out.println("a = " + a); // a = a
System.out.println("b = " + b); // b = ab