当前位置: 动力学知识库 > 问答 > 编程问答 >

Java HashMap does not return right value

问题描述:

I have a problem, this code:

import java.util.HashMap;

import java.util.Map;

import java.util.Random;

public class BankDatabase {

private Map<String, BankUser> bankUsers = new HashMap<String, BankUser>();

public boolean add(String name, String lastName, String username, String password) {

Random random = new Random();

String accountNumber = "";

for (int i = 0; i < 9; i++) {

accountNumber = accountNumber + random.nextInt(9);

}

BankUser user = new BankUser(name, lastName, accountNumber, username, password);

if (!bankUsers.containsKey(username)) {

bankUsers.put(username, user);

return true;

} else {

return false;

}

}

public Map<String, BankUser> getBankUsers() {

return bankUsers;

}

}

The problem comes that this block of code only return true, even if it should not, it does not return a false. I use this for JFrame, and I ask a boolean if false, needs to say that user already exists.

网友答案:

My two cents, I am assuming this is what he is actually looking for

  1. Considering that the database is a global app, I've made it a singleton.
  2. You have to be very careful while using String as Key. Keep in mind, both "myUserName" and "MYUSERNAME" would be allowed as they both are different. Either store the key in lowercase or in uppercase, so as to avoid "semantic" duplication of keys.
  3. Further steps have to be taken to prevent inconsistent state of the map and this could be achieved by making the HashMap thread safe.

    public class BankDatabase {
    
        private static BankDatabase instance;
    
        // It would contain a hash map of username and his BankUser bean
        private Map<String, BankUser> users;
    
        private BankDatabase() {
            users = new HashMap<String, BankUser>();
        }
    
        public boolean synchronized addUser(String username, BankUser bankUser) {   
    
          // When you are using String as the key, 
          // ensure that you are storing it as only on lowercase or uppercase 
          //
          // Note feel free to write additional code here 
          // depending on your needs
    
          if(users.containKey(username.toLowerCase())){
               return false;
          }
          users.put(username.toLowerCase(), bankUser);
          return true;
    
        }
    
        public BankUser getBankUserByUsername(String username) {
            return users.get(username.toLowerCase());
        }
    
        public static synchronized BankDatbase getInstance() {
            if (instance == null) {
                 instance = new BankDatabase();
            }
          return instance;
        }
    }
    

Note: There are of course other variations of writing better singleton, adding more thread safety feature, but my idea was to provide what could be done to improve the code conceptually and from design perspective.

分享给朋友:
您可能感兴趣的文章:
随机阅读: