Avoiding overwriting objects in ArrayList

别等时光非礼了梦想. 提交于 2019-12-18 04:23:09

问题


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<ValidateUser> personer = new ArrayList<ValidateUser>();
ValidateUser newUser = new ValidateUser();
    newUser.setUser("administrator");
    newUser.setPass("asdf123");
    newUser.setBalance(0.8);
    newUser.setType("admin");
    personer.add(newUser);

Got a nice array-list going on, but if i add more "newUsers" to the ArrayList, they seem to overwrite each other. I don't want to make a newUser1, newUser2 object, since later in my program, I have to be able to add new users, directly from the program.

How to achieve this?

ValidateUser:

public class ValidateUser {

private String username;
private String password;
private double balance;
private String role;


public void setUser(String user) {
    username = user;
}
public void setPass(String pass) {
    password = pass;
}
public void setBalance(double rating) {
    balance = rating;
}
public void setType(String type) {
    role = type;
}

public String getUsername() {
    return username;
}
public String getPassword() {
    return password;
}
public double getBalance() {
    return balance;
}
public String getRole() {
    return role;
}

}


回答1:


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);



回答2:


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.



来源:https://stackoverflow.com/questions/20168524/avoiding-overwriting-objects-in-arraylist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!