Sam Ho
Sam Ho

Reputation: 21

Printing a TreeMap value which is an Object

I am trying to print out a treemap with integer keys and Employee values. Each Employee object should be contains a (string)last name, a (string)first name, a (Integer)ID and a (string)performance scale. I already finished class Employee. However, my output comes out with values as locations.

Map(Integer, Employee) e = new TreeMap(Integer, Employee) ();

    Employee e1 = new Employee("Puppy", "Nguyen", new Integer(345), "4");
    e.put(e1.getID(), e1);
    Employee e2 = new Employee("Kitty", "Thompsons", new Integer(123), "2");
    e.put(e2.getID(), e2);
    Employee e3 = new Employee("Cubby", "Gonzalez", new Integer(234), "5");
    e.put(e3.getID(), e3);

    System.out.println("Original Employee-typed TreeMap: ");

    for(Map.Entry<Integer, Employee> entry : e.entrySet())
    {
        System.out.println("ID: " + entry.getKey());
        System.out.println("Employee: " + entry.getValue());
    }

My output:

Original Employee-typed TreeMap:

ID: 123

Employee: Employee@fef18a5d

ID: 234

Employee: Employee@ec71836a

ID: 345

Employee: Employee@89120ee

Upvotes: 1

Views: 2178

Answers (3)

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

you can do like this

for(Map.Entry<Integer, Employee> entry : e.entrySet())
{
    System.out.println("ID: " + entry.getKey());
    Employee employee = entry.getValue();
    System.out.println("Employee: " + employee.getFirstName() +" "+employee..getLastName());
}

or

You need to add toString() method in the Employee class like below

class Employee{


    @Override
    public String toString() {
         return this.firstName + " " + this.lastName;
    }
}

Upvotes: 0

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

You have to override the toString() method in Employee. Right now you're looking at

getClass().getName() + '@' + Integer.toHexString(hashCode()), which obviously doesn't have a lot of meaning.

@Override
public String toString(){
 return this.name; // Or however the local field is declared
}

Upvotes: 2

Frenchman
Frenchman

Reputation: 21

Java is printing the class name and memory address of your Employee objects because they do not have a String toString() method. Implement it to provide a description of the employee and it will be used when you print, or debug, etc.

E.g.:

@Override
public String toString() {
    return this.getFirstName() + ' ' + this.getLastName() +
        " (Perf. Scale: " + this.getPerformanceScale() +')';
}

Upvotes: 0

Related Questions