检查HashMap密钥是否存在时出错

时间:2013-12-17 14:34:48

标签: java hashmap key

我目前正在使用散列图存储有关当前帐户的信息。

以下是我在一种方法中所拥有的:

HashMap<String, Account> account = new HashMap<String, Account>(); 
    if (Account.validateID(accountID))  {
        System.out.println("Account ID added");
        Account a = new Account(cl,accountID, sortCode, 0);
        account.put(accountID, a); //add to HashMap     
    }

这似乎工作正常。然后我用另一种方法:

public void enterTransaction()
{   
    String tAccountID = JOptionPane.showInputDialog(this,
    "Enter valid accountID", "Add Account", 0); 
    System.out.println("Check if accountID exists: " +  account.containsKey(tAccountID)); //testing if accountID exists - currently not working
    Date currentDate = new Date();
    System.out.println("Date and time of transaction: " + currentDate); //prints the date and time of transaction

} 

基本上,我正在尝试这样做,以便当我进入事务时,它会检查为事务输入的AccountID是否等于来自HashMap的AccountID(密钥)。

我尝试使用enterTransaction()的第6行来检查它是否存在。但是,即使我知道我两次输入相同的accountID,它似乎也不起作用并且总是说“假”。我也试过用这句话:

System.out.println(account.get(accountID));

这似乎给了我“Account @ cb1edc”?

对于这个冗长的问题感到抱歉,这是一个简单的问题,我真的只是觉得我会给你所有的信息。感谢。

1 个答案:

答案 0 :(得分:2)

这是正确的行为。 account.get(accountID)返回一个Account对象,该对象是从JVM内存转储打印的。

为了获得一些清晰的输出,Account类需要一个toString方法,该方法返回一个包含有用信息的String。

当您尝试将对象打印到控制台时,JVM会自动搜索toString方法并使用该方法对对象进行字符串化(使其具有人工可读性),如果它无法找到该对象的方法,则会打印出JVM的对象该对象的内部内存id看起来有点像垃圾。试试这个:

public String toString() {
    return "This is account " + this.id; // or something like this
}
相关问题