Java:关于foreach的疑问

查看:129
本文介绍了Java:关于foreach的疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

实体类

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的,和这个是一样的道理:

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;
}

这篇关于Java:关于foreach的疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆