输出结果是什么?为什么 ArrayList/any Collection 会这样?

What will be the output and why ArrayList/ any Collection behave like this?

下面说的是我的beanclass:

public class Employee {

    private String name = null;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

这是我的主class:

import java.util.ArrayList;

public class MainClass {

    public static void main(String[] args) {

        Employee employee = new Employee();
        employee.setName("First name");

        ArrayList<Employee> empList = new ArrayList<Employee>();
        empList.add(employee);

        employee.setName("Last name");

        for (Employee emp : empList) {
            System.out.println(emp.getName());
        }
    }
}

当我执行输出时:Last name

我的问题是:

  1. 据我所知 Java 是 pass-by-value 或者更确切地说 pass-by-copy-of-the-variable-value 然后复制 employee 对象已保存在 ArrayList 中或它引用了 Employee 的原始对象,因为对象值正在更改 添加到 ArrayList?
  2. 后到 Last name
  3. 每个集合都是这样吗?

employee 引用的副本已保存在 ArrayList 中,但由于它引用相同的 Employee 实例,稍后通过 employee 更改实例引用影响存储在 ArrayList.

中的元素

是的,每个 Collection 都是这样,因为 Collection 不会创建传递给它们的实例的副本,它们只是存储对这些实例的引用。

  1. As I know Java is pass-by-value or rather pass-by-copy-of-the-variable-value then does the copy of employee object was saved in the ArrayList or it references the original object of Employee as the object value is getting changed to Last name after adding to ArrayList?

引用将按值传递。因此,将有 2 个引用指向同一个 Employee 实例。一个参考文献是 employee,另一个参考文献是 arraylist.

  1. Does every Collection behave this way?

是的。实际上,这是 NOT 一个 属性 集合。这就是 java 的设计方式。所有 mutable 引用类型都以这种方式运行。

局部变量employee和列表的第一个元素是对同一对象的两个不同引用。这就是为什么在其中一个上修改引用对象(例如,通过 setName)将通过另一个可见。

但是,如果您通过分配不同的引用来替换引用,它不会影响另一个引用。

例如:

employee = new Employee();
employee.setName("Vishrant");

现在employee和列表的第一个元素引用不同的个对象,所以数组中的元素不会被调用"Vishrant"