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
.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With