添加的项目值更改后,项目属性清除



我有一个列表,当我清除列表的Notes属性后将其添加到列表中,就像下面的例子一样,它也清除了stdList的添加项。我真的不明白为什么?请帮帮我:

List<Student> stdList = new List<Student>();
Student std = new Student();
std.Notes = new List<string>();
std.Notes.Add("EE");
stdList.Add(std);
std.Notes.Clear();

当您添加Student对象时,它会在列表中添加对该对象的引用。您添加的引用仍然指向您修改过的同一个对象。因此,对对象的任何更改都将反映在列表中。

下面是demo:

StringBuffer sb = new StringBuffer("aa");
List<StringBuffer> list = new ArrayList<StringBuffer>();
list.add(sb);
System.out.println(list);
sb.append("bb");
System.out.println(list);
sb = null;
System.out.println(list);
输出:

aa
aabb
aabb

不要忘记,当你处理像字符串这样不可变的对象时,一个新的对象将在更改操作时被创建。当您在其他地方获得新对象时,旧对象仍在列表中

最新更新