2013-12-17 118 views
1

我目前使用散列图存储有关当前帐户的信息。检查HashMap密钥是否存在时出错

以下是我有一个方法:

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 

} 

基本上,我试图让这个当我去进入一个交易,它会检查已输入的交易帐户ID等于从的AccountID HashMap(关键字)。

我尝试使用enterTransaction()的线6,以检查它是否存在。然而,即使当我知道我已经同时输入了相同的accountID时,它似乎并不工作,并总是说“错误”。我也尝试使用此声明:

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

这似乎给我“帐户@ cb1edc”?

很抱歉的长期问题,这是一个简单的问题其实只是想我给你所有的信息,我可以。谢谢。

+0

你能告诉你'Account'类吗? –

+0

'Account'类中有'toString'方法吗? –

+0

为什么它会存在,如果你还没有把它放在地图上呢? –

回答

2

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

为了得到一些清晰的输出,账户类需要返回有用信息的字符串一个toString方法。

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

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

快速回复!不知道为什么我没有考虑使用toString。添加到HashMap后我尝试做“System.out.println(account.get(toString()));” 。但现在我收到null – StackMeUp123

+0

排序它现在欢呼 – StackMeUp123