0

I have two Classes. one DAO that has an Arrraylist of Users (user is instace of User class) and one method in another class that checks if there is a user with our input name or not How can I use Hashmap (usernames, User) instead of Arraylist of Users?

public class UserDAO {
private static UserDAO instance;
private static String fileName = "sources/users.aaa";
//--------------------------------------------------------
private UserDAO(){

}
//--------------------------------------------------------
public boolean storeUsers(ArrayList<User> Users){
    return IOFile.writeObject(Users, fileName);
}

//--------------------------------------------------------
public ArrayList<User> getUsers(){
    ArrayList<User> Users = (ArrayList<User>) IOFile.readObject(fileName);
    return Users;
}
//--------------------------------------------------------
public static UserDAO getInstance(){
    if(instance == null)
        instance = new UserDAO();
    return instance;
}

}

and one method in another class that checks if there is a user with our input name or not:

User user = new User(firstName, lastName, userName, password);
            ArrayList<User> users =  UserDAO.getInstance().getUsers();
            for (User user2 : users) {

                if (user.equals(user2)){
                    system.out.println ("Error!!");
                    return;
                }
            }
            users.add(user);
            UserDAO.getInstance().storeUsers(users);
1
  • If you want map one Object to another then use HashMap. But to know what it is like you may cover my tutorial on HashMap at first Commented Jul 25, 2013 at 11:10

1 Answer 1

2

In this case, since you're just trying to check if the user exists, you could use a HashSet. A set has constant time lookups. So instead of your loop, it would just be users.contains(user).

You could use a map if you were looking up by something other than the actual User object, e.g. a mapping of names to users.

In either case, if you're using collection where you're checking contains, you must implement both equals and hashCode properly.

Sign up to request clarification or add additional context in comments.

2 Comments

I want to have a map with key: username and Value: User.
in that case you can use a hashmap

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.