Looping to add objects in the list is always adding an object

1. When an object is new, the ID of the object is uniquely determined; when adding an object to a list, what is put into the list is actually a reference to the object; and each cycle is simply a simple set of the properties of the object, set new The attribute value of , and the object added into the list is still the same object id, that is, the same object;
2. So after each add, the list finds that the object reference is the same as the previous element, and it overwrites the previously added object. So the objects in the list after the loop are duplicate objects.
3. If you want to avoid this problem, you only need to ensure that the object references are different each time you add, that is, re-new an object every time you loop.
4. // The new object should be placed in the for loop, and a new object will be re-created once in each loop


        List<User>  list = new ArrayList<User>();
        User user = new User();
        for(int i=0;i<10;i++ ){
            user.setUsername("test"+i);
            user.setPassword("password"+i);
            
            list.add(user);
        }
        
// Each element of the list set obtained above is the object of the last cycle, repeating, each time the set changes the value of the same address object
        
// Solution: Take the new object into the loop body, you can get the expected result, create a new address each time to store the new object

        List<User>  list = new ArrayList<User>();
        for(int i=0;i<10;i++ ){
            User user = new User();
            user.setUsername("test"+i);
            user.setPassword("password"+i);
            
            list.add(user);
        }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326565193&siteId=291194637