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
1.0k views
in Technique[技术] by (71.8m points)

java - How to create an arraylist class that can store multiple objects?

I am a self-learner. Currently, I am making a GUI project in which I need a matrice-type database.

I would like to learn how I can create a class that can store multiple objects in an arraylist.

Here is my sample code. Please note that this is just my attempt. This code is not finalized, and it's not working.

Thank you for your kind help.

    import java.util.ArrayList;
    import java.util.List;

}}

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I think a better way to do this is to create a user info class to store the information of a particular user like this.

// I made them all public but this might not be a good idea!
class UserInfo {
    String user;
    String pass;
    String secretCode;
}

And you put it into an ArrayList.

ArrayList <UserInfo> InfoList = new ArrayList<UserInfo> ();    

Then for your current methods, you can do

// Not so sure what you want to do in this method... so you get to figure out that yourself!
public void userInternalDatabase (UserInfo info) {

    this.user = info.user;
    this.pass = info.pass;
    this.secretCode = info.secretCode;
}

public void addUser(String i, String j, String k) {
    UserInfo newUser = new UserInfo();
    newUser.user = i;
    newUser.pass = j;
    newUser.secretCode = k;
    InfoList.add(newUser);
}

public Object findUsername(String a)  
{    
    for (int i=0; i <InfoList.size(); i++) {
        if (InfoList.get(i).user.equals(a)){
             return "This user already exists in our database.";
        }
    }
    return "User is not founded."; // no Customer found with this ID; maybe throw an exception
}

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

...