1. 程式人生 > >通過遍歷的方式可以改變陣列中物件的值

通過遍歷的方式可以改變陣列中物件的值

public class EurekaServerApplication {

    public static void main(String[] args) {

        SpringApplication.run(EurekaServerApplication.class, args);

        List<user> list = new ArrayList<>();
        user u1 = new user();
        u1.setName("san");
        u1.setAge(10);
        list.add(u1);
        user u2 = new user();
        u1.setName("san");
        u1.setAge(10);
        list.add(u1);
        user u3 = new user();
        u1.setName("san");
        u1.setAge(10);
        list.add(u1);
        for (user user : list) {
            user.setName("tom");
        }

        for (user user : list) {
            System.out.println(user.toString());
        }
    }

}
class user{
    private String name;
    private Integer age;


    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "user{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}