Krow Caw
Krow Caw

Reputation: 47

Trouble using HashMap containing Objects

Please pardon my bad English

I am trying to create a HashMap with a String as a key, and an Object as parameter, which I want to initialise each time the program runs so that its added to a new key in the HashMap.

The problem is, that not all values are returned, and namely the second, gives back a weird output.

package javaex1;
import java.util.*;

public class Javaex1 {

public static void main(String[] args) {

    Person obj = new Person("Eminem", "Male");
    HashMap<String, Person> MapPerson = new HashMap<String, Person>();
    MapPerson.put("Eminem", obj);

    System.out.println(MapPerson);
  }    
}

The object

package javaex1;


public class Person {


String Name;
String Gender;


public Person (String name, String Gend) {

    this.Name = name;
    this.Gender = Gend;
}    


public String getName() {
    return Name;
}

public String getGender() {
    return Gender;
}


}

Any help or hint is greatly appreciated! Thank you in advance for your time!

The expected results should be "Eminem Male". Instead what I get is this:

{Eminem=javaex1.Person@2a139a55}

Upvotes: 1

Views: 174

Answers (3)

jaseel_ep
jaseel_ep

Reputation: 58

This happens because you are trying to print an Object, An Object when printed gives the default toString implementaion of Object class , which is shown below

// implementation of toString in Object class

 public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

This is what you can see in your current output .

You should ovverride toString method in Person class like this.

    public String toString() {
    return this.Name + " " + this.Gender; 
}

So that it returns the name and gender

Upvotes: 2

Pavel Smirnov
Pavel Smirnov

Reputation: 4799

You're printing the MapPerson object, not the Person one.

Your code should be:

Person person = MapPerson.get("Eminem");
System.out.println(person.getName() + " " + person.getGender());

Upvotes: -1

Andronicus
Andronicus

Reputation: 26026

You should override toString method in Person class. Like that:

@Override
public String toString() {
    return this.Name + " " + this.Gender;
}

Upvotes: 1

Related Questions