實體類
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
提交
取消