如何创建一个可以存储多个对象的arraylist类? [英] How to create an arraylist class that can store multiple objects?

查看:46
本文介绍了如何创建一个可以存储多个对象的arraylist类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个自学者.目前,我正在制作一个 GUI 项目,其中需要一个矩阵型数据库.

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.

感谢您的帮助.

    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
}

这篇关于如何创建一个可以存储多个对象的arraylist类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆