[英]hashmap using a “employee class” as the value
我創建了一個HashMap
,其中的鍵是Integers
,值是Employee
類。 Employee
包含員工的名字,姓氏和地址。 我在打印出值時遇到問題。 這是我嘗試過的。
employees.put(5, e1);
String test=employees.get(5).toString();
System.out.println(employees.toString());
System.out.println(test);
輸出:
{5=identitymanagement.Employee@6da264f1}
identitymanagement.Employee@6da264f1
我究竟做錯了什么?
看一下你的代碼
String test=employees.get(5).toString();
這將在您的哈希圖中使用鍵5
捕獲該項目,然后調用該對象的toString
方法。 當前對象的行為方式意味着您沒有重寫該方法,這就是為什么它在內存中打印出對象地址的原因。
System.out.println(employees.toString());
這將嘗試打印出HashMap
對象。 與Employee
類一樣,HashMap不會覆蓋它的toString
方法,因此它只是打印出內存中的對象引用。
一個解法
在輸出類的詳細信息時,約定是重寫toString()
方法。 看起來像這樣:
public String toString()
{
return "name: " + name;
}
當您將此方法放在您的類中時,可以調用toString
方法,它不僅會打印出對象的內存地址,這就是當前的操作:)
使用此代碼時,您要做的就是將對象傳遞給System.out.println
方法,其余的將由它完成:
Employee e = employees.get(5);
System.out.println(e);
正確的方法是
Employee e = employees.get(5); // return's Employee object stored in map with key 5
String firstName = e.firstName;
String lastName = e.lastName;
String address = e.address;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.