Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

java - Avoiding overwriting objects in ArrayList

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

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...