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

℡╲_俬逩灬. 提交于 2019-11-28 04:51:39

问题


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;

}}


回答1:


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
}


来源:https://stackoverflow.com/questions/15423483/how-to-create-an-arraylist-class-that-can-store-multiple-objects

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