package com.test.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
class SerializableBean implements Serializable{
private static final long serialVersionUID = 1L;
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
public class BeanMain {
private static void changeString() {
List<String> l = new ArrayList<String>();
String a = "SS";
l.add(a);
System.out.println(l.get(0));
a = "zzz";
System.out.println(l.get(0));
}
private static void changeObject() {
List<SerializableBean> l = new ArrayList<SerializableBean>();
SerializableBean e = new SerializableBean();
e.setTest("SS");
l.add(e);
System.out.println(l.get(0).getTest());
e.setTest("zzz");
System.out.println(l.get(0).getTest());
}
public static void main(String[] args) {
changeString();
changeObject();
}
}
输出结果:
SS
zzz
SS
SS
由输出结果可见,changeString两个结果一样,changObject达到了想要的效果。changeString:原因是动态数组引用a="ss"是指向"ss"的内存地址,a="zzz"时,a指向"zzz"的地址,而动态数组却还指向"ss"的地址。changeObject方法中动太数组 l 一直是指向 e的地址,所以e中的成员变量值改变时,l 中的元素的成员变量也改变(是相同的对象)。
|