简体   繁体   English

使用“员工类别”作为值的哈希图

[英]hashmap using a “employee class” as the value

I created a HashMap where the keys are Integers and the values are of the Employee class. 我创建了一个HashMap ,其中的键是Integers ,值是Employee类。 Employee contains the employee's first name, last name and address. Employee包含员工的名字,姓氏和地址。 I am having issues with printing out the values. 我在打印出值时遇到问题。 Here is what i tried. 这是我尝试过的。

employees.put(5, e1);

String test=employees.get(5).toString();
System.out.println(employees.toString());
System.out.println(test);

output: 输出:

{5=identitymanagement.Employee@6da264f1}
identitymanagement.Employee@6da264f1

What am I doing wrong? 我究竟做错了什么?

A look at your code 看一下你的代码

String test=employees.get(5).toString();

This will grab the item with the key 5 in your hashmap, then call that object's toString method. 这将在您的哈希图中使用键5捕获该项目,然后调用该对象的toString方法。 The way your object is behaving at the moment implies you have no overridden that method, which is why it is printing out the objects address in memory. 当前对象的行为方式意味着您没有重写该方法,这就是为什么它在内存中打印出对象地址的原因。

System.out.println(employees.toString());

This will attempt to print out the HashMap object. 这将尝试打印出HashMap对象。 In the same vain as your Employee class, HashMap does not override it's toString method, so it simply prints out the objects reference in memory. Employee类一样,HashMap不会覆盖它的toString方法,因此它只是打印出内存中的对象引用。

A solution 一个解法

The convention, when outputting the details of a class, is to override the toString() method. 在输出类的详细信息时,约定是重写toString()方法。 This would look something like this: 看起来像这样:

public String toString()
{
   return "name: " + name;
}

When you place this method in your class, you can call the toString method and it won't just print out the memory address of the object, which is what it is doing at the moment :) 当您将此方法放在您的类中时,可以调用toString方法,它不仅会打印出对象的内存地址,这就是当前的操作:)

When using this code, all you have to do is pass the object to the System.out.println method and it will do the rest: 使用此代码时,您要做的就是将对象传递给System.out.println方法,其余的将由它完成:

Employee e = employees.get(5);
System.out.println(e);

The correct way is 正确的方法是

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM