public class ListDemo2 {
public static void main(String[] args) {
Student stu1 = new Student("01", "张三", 56);
Student stu2 = new Student("02", "初夏", 45);
Student stu3 = new Student("03", "易烊千玺", 23);
Student stu4 = new Student("04", "王俊凯", 67);
Student stu5 = new Student("05", "王一博", 58);
List<Student> list = new ArrayList<Student>();
list.add(stu1);
list.add(stu2);
list.add(stu3);
list.add(stu4);
list.add(stu5);
System.out.println(list.toString());
for (int i = 0; i < list.size(); i++) {
Student stu = list.get(i);
stu.setAge(18);
}
System.out.println(list.toString());
}
}
运行结果如下:
[Student{sno='01', name='张三', age=56}, Student{sno='02', name='初夏', age=45}, Student{sno='03', name='易烊千玺', age=23}, Student{sno='04', name='王俊凯', age=67}, Student{sno='05', name='王一博', age=58}]
[Student{sno='01', name='张三', age=18}, Student{sno='02', name='初夏', age=18}, Student{sno='03', name='易烊千玺', age=18}, Student{sno='04', name='王俊凯', age=18}, Student{sno='05', name='王一博', age=18}]
以下循环 list,将集合中的stu对象的属性值age设置成18,为何不用新的集合去存更新age属性后的stu对象,而直接打印原list即可?
原因很简单:stu对象更新了,但它指向的内存地址没变,还是存放在原来的list中,所以打印原来的list即是更新属性值之后的对象。