Avoiding overwriting objects in ArrayList

前端 未结 2 1019
暗喜
暗喜 2020-12-16 07:52

Stackers. I\'ve been searching the site for my question, but didn\'t find what I was looking for. I\'m stuck with this code:

public class Users{
ArrayList<         


        
相关标签:
2条回答
  • 2020-12-16 08:45

    If I understood right you're adding new users this way:

    ValidateUser newUser = new ValidateUser();
        newUser.setUser("administrator");
        newUser.setPass("asdf123");
        newUser.setBalance(0.8);
        newUser.setType("admin");
        personer.add(newUser);
    
        newUser.setUser("different admin");
        personer.add(newUser);
    

    however this way the object points to the same reference, thus you must do the following to instantiate a new object:

     newUser = new ValidateUser();
     newUser.setUser("foo");
     personer.add(newUser);
    
    0 讨论(0)
  • 2020-12-16 08:49

    As long as you new ValidateUser() you should be fine. In other words, if you instantiate a new object of the ValidateUser type, and add it to your ArrayList.

    You did not clearly explain what you exactly do, but my first guess is that you use the same reference all over again... :)

    Example how to make 10 new ValidateUser objects:

    // Let's make 10 objects of ValidateUser type
    ValidateUser tmpVuser = null;
    for (int i = 0; i < 10; i++) {
        tmpVuser = new ValidateUser(); // notice: we always create a new instance
        tmpVuser.setUser("user" + i);
        tmpVuser.setPass("changeme" + i);
        tmpVuser.setBalance(0.8);
        tmpVuser.setType("admin");
        personer.add(tmpVuser);
    }
    

    However, it is worth of notice that if ValidateUser was an immutable type (more about it here: http://www.javapractices.com/topic/TopicAction.do?Id=29 ), your code would probably work fine.

    0 讨论(0)
提交回复
热议问题