如何创建一个可以存储多个对象ArrayList类?多个、创建一个、对象、ArrayList

2023-09-07 14:06:06 作者:、安于现状

我是一个自我学习。现在,我想提出一个GUI项目中,我需要一个矩阵的计算型数据库。

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

我想了解我怎么可以创建一个ArrayList存储多个对象的类。

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

下面是我的示例code。请注意,这只是我的尝试。这code未最终确定,而且它不工作。

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

感谢您的热心帮助。

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

}}

推荐答案

我觉得更好的方式来做到这一点是创建一个用户信息类来存储这样的特定用户的信息。

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

和你把它变成一个ArrayList

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
}