亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java:關于foreach的疑問

Java:關于foreach的疑問

郎朗坤 2019-02-24 00:32:32
實體類 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;
}

查看完整回答
反對 回復 2019-03-01
?
白豬掌柜的

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,而僅僅是它的一個"副本"。

查看完整回答
反對 回復 2019-03-01
?
隔江千里

TA貢獻1906條經驗 獲得超10個贊

你這里說foreach,然后寫一個for遍歷,for遍歷的時候,遍歷到的結果放到新變量Student student里面,怎么會是指針?你這里面的

for(Student student : list) {
}

也就是說從list遍歷到變量存到新變量Student student里,每次遍歷都會放到同一個變量里,后一次遍歷的結果會覆蓋前一次的Student student結果

查看完整回答
反對 回復 2019-03-01
  • 3 回答
  • 0 關注
  • 488 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號