实体类
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遍历时访问的不是每个元素的引用吗?
Java是call by value的,和这个是一样的道理: