ArrayList的add方法的源码,可以看到仅仅是把对象用’='号复制了一下,但是更改如果更改外边的e的话,ArrayList里的对象就会随之改变
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
测试:
public class SayHello{
public static void main(String [] args) throws CloneNotSupportedException {
Test t = new Test("hello");
ArrayList<Test> arry = new ArrayList<SayHello.Test>();
arry.add(t);
Test newT = arry.iterator().next();
newT.setStr("hha");
System.out.println(t.str);
}
public static class Test implements Cloneable{
private String str = "hello";
public Test(String str){
this.str = str;
}
public void setStr(String newStr) {
this.str = newStr;
}
}
}
输出结果为hha,所以往ArrayList里添加对象的时候最好new 出来一个或者clone一个。