4

I am making a GUI project in which I need a matrice-type database.

How can I create a class that can store multiple objects in an ArrayList?

3
  • so basically you want to store user information in ArrayList? Commented Mar 15, 2013 at 2:03
  • 1
    This example is begging for you to create a class named User to encapsulate data about users. Once you create a User class, you can create an ArrayList of Users. This is an important concept in Object Oriented Programming. Commented Mar 15, 2013 at 2:24
  • SuKu: Yes. Jahroy: Thanks for your advice. Commented Mar 15, 2013 at 2:32

1 Answer 1

11

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your help. So, if I want to retrieve the username data, what should I do? Also, would the InfoList have three columns: username, password, and secret code?? Thanks.
you could use InfoList.get(index) which index is an integer to retrieve an UserInfo object, or you could use iterator to search object which has the same info that you're searching for. You can access the data by using InfoList.get(i).user, InfoList.get(i).pass, InfoList.get(i).secretCode. And again note that public variables might not be a good idea!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.