Get value from Hashmap by user object

I have hashmap

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

Then I add a new pair to it.

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

How can I get this pair from this card? I have tried:

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

But as a result, I have null , while I was expecting 5 .

+5
source share
3 answers

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

So, suppose your Man class looks something like this:

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

If you ask the IDE to create methods for you, you get the following:

 @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); } 
+5
source

You need something unique that defines the Man object. In your case, this seems to be name .

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

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

+2
source

HashMap is working fine. Just because you create two new objects with the same name does not mean that the computer considers them to be the same object.

Try the following:

 man1 = new Man("John"); man2 = new Man("John"); if (man1 == man2) { System.out.println("Equal"); } else { System.out.println("Not equal"); } 

You will get β€œnot equal” because the computer checks to see if they are exactly the same object, and not just the same.

Each time you use the "new" keyword, you declare a new object, and the computer gives it a unique address.

Try the following:

 man1 = new Man("John"); HashMap<Man, Double> myList = new HashMap<>(); myList.put(man1, "5.00"); System.out.print.ln(myList.get(man1)); 

you will see that now you get "5.00" back because you are actually giving it the exact object, which is the key on the map.

You will need to manually determine how you decide that the two β€œmen” are equal if you want the behavior to work that way. You might be better off using the full name as the key, as this will usually be unique and work less for you.

+1
source

Source: https://habr.com/ru/post/1261527/


All Articles