简体   繁体   中英

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. Employee contains the employee's first name, last name and address. 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?

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. 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. 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.

The convention, when outputting the details of a class, is to override the toString() method. 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 :)

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:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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