Kyle Rohlfing Kyle Rohlfing - 1 month ago 5
Java Question

Get command of a hashmap with a parameter different than the key in the hashmap?

I have a custom class as my key in my hashmap like so

// In the main function
HashMap<Drink, boolean> drinkMap = new HashMap<>();

// What I would like to be able to do:
drinkMap.get("beer");

// My drink Class which is used as the key
public class Drink implements Comparable<String> {
private String name;
private String info;

public String getName() {
return Name;
}

public Drink(String name, String info) {
this.name = name;
this.info = info;
}
}


What I want to do is have the get method for the hashmap compare the string that is passed in to Drink.name and if they are the same then return that hashmap entry, but I cannot figure out how to get this to work.

I tried implementing the equals and hashcode methods in my Drink class like so:

@Override
public int hashCode() {
return Name.hashCode();
}

@Override
public boolean equals(Object o) {
return o instanceof String && o.equals(Name);
}


But when I would do hashMap.get("beer") it kept returning null even though I know there exists a Drink object with the name "beer" in the map.

Answer

This is a terrible idea. You should always query a map with the same type (or a subtype thereof) as the intended key. Not doing that only opens you up to problems (as I'm sure you've started to notice).

You should consider either making the key of your map a String type, or querying your map by Drink.

(As to why your specific case isn't working: "beer".equals(drink) != drink.equals("beer").)