List集合保存对象,存储的是对象的地址
下面是先创建对象后,不断改变对象的名称保存到集合里
public static void test() {
List<Employee> nameList = new ArrayList<>();
Employee employee = new Employee();
for (int i = 0; i < 3; i++) {
employee.setName("张"+i);
nameList.add(employee);
}
nameList.forEach(System.out::println);
}
结果如下,全是相同的姓名
List集合保存对象,存储的是对象的地址
public static void test2() {
List<Employee> nameList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
Employee employee = new Employee();
employee.setName("张"+i);
nameList.add(employee);
}
}