实体类
public class Student {
private int id;
private String name;
public Student() {
}
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
foreach遍历
public class Client {
public static void main(String[] args) {
Student one = new Student(1, "one");
Student two = new Student(2, "two");
Student three = new Student(3, "three");
List<Student> list = new ArrayList<Student>();
list.add(one);
list.add(two);
list.add(three);
for (Student student : list) {
student = null;
}
System.out.println(list); // 输出结果:[Student@4aa594e1, Student@3cd16610, Student@5783c3a1]
}
}
为什么遍历时将对象赋为null输出时仍存在哪?foreach遍历时访问的不是每个元素的引用吗?
3 回答
潇湘沐
TA贡献1816条经验 获得超6个赞
Java是call by value的,和这个是一样的道理:
public static void main(String[] args) {
Object obj = new Object();
process(obj);
System.out.println(obj);//并不是null
}
private static void process(Object obj) {
obj = null;
}
白猪掌柜的
TA贡献1893条经验 获得超10个赞
是这样的,在for循环内,
for (Student student : list) {
student = null;
}
当执行 Student student : list 时,在栈中push了一个指向Student实例对象的Student引用对象(list.get(0)也指向当前实例对象), 然后执行 student = null; 把栈中的这个临时引用对象变量 指向null,并不是将list.get(0) 的引用变量指向null,而仅仅是它的一个"副本"。
隔江千里
TA贡献1906条经验 获得超10个赞
你这里说foreach,然后写一个for遍历,for遍历的时候,遍历到的结果放到新变量Student student里面,怎么会是指针?你这里面的
for(Student student : list) {
}
也就是说从list遍历到变量存到新变量Student student里,每次遍历都会放到同一个变量里,后一次遍历的结果会覆盖前一次的Student student结果
添加回答
举报
0/150
提交
取消
