我有一个问题,这段代码:
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;
}
}
问题是这个代码块只返回true
,即使它不应该返回,它也不会返回false
。我将此用于JFrame
,我问boolean
如果false
,则需要说用户已经存在。
答案 0 :(得分:1)
我的两分钱,我假设这是他实际上正在寻找的东西
必须采取进一步措施来防止地图的不一致状态,这可以通过使HashMap线程安全来实现。
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;
}
}
注意:当然,编写更好的单例,添加更多线程安全功能的其他变体,但我的想法是提供从概念上和从设计角度改进代码的方法。