Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from Hashmap by user object

I have such hashmap

HashMap<Man, Double> d = new HashMap<>();

Then I add new pair into it.

d.put(new Man("John"), 5.);

How can I retrieve this pair from this map? I tried to do:

Man man = new Man("John");
System.out.println(d.get(man));

But as a result I have null while I expected 5.

like image 998
Kenenbek Arzymatov Avatar asked Dec 19 '16 20:12

Kenenbek Arzymatov


2 Answers

This can only work if you override the methods equals(Object obj) and hashCode() in your class Man to allow your HashMap to understand that even if they are not the same instances, they have the same content and should be considered as the same key in your map.

So assuming that your class Man is something like:

public class Man {
    private final String name;

    public Man(final String name) {
        this.name = name;
    }
    ...
}

If you ask your IDE to generate the methods for you, you would get something like this:

@Override
public boolean equals(final Object o) {
    if (this == o) return true;
    if (o == null || this.getClass() != o.getClass()) return false;
    final Man man = (Man) o;
    return Objects.equals(this.name, man.name);
}

@Override
public int hashCode() {
    return Objects.hash(this.name);
}
like image 119
Nicolas Filotto Avatar answered Sep 23 '22 09:09

Nicolas Filotto


You need to have something unique that defines the object Man. In your case, it appears to be -name.

So you override the equals() method and similarly the hashcode() methods in your Man class using name as the unique identifier.

Since name is a string you can delegate the task to similar methods in the String class.

like image 41
Ravindra HV Avatar answered Sep 20 '22 09:09

Ravindra HV