AeriaGlorisia AeriaGlorisia - 14 days ago 6
Java Question

How do you search a hashmap with an object as a key?

Say we have class RegistrationPlate:

public class RegistrationPlate {
private final String regCode;
private final String country;

public RegistrationPlate(String country, String regCode) {
this.regCode = regCode;
this.country = country;
}

public String getRegCode() {
return this.regCode;
}

public String getCountry() {
return this.country;
}

@Override
public String toString() {
return country + " " + regCode;
}


and I have a hashmap with RegistrationPlate as its key, and owner as its value. If I wanted to search this hashmap given a RegistrationPlate object as a parameter how would I do so? This is how I initially approached it:

HashMap<RegistrationPlate, owner> vehicleRegister = new HashMap<RegistrationPlate, owner>();


public String getOwner(RegistrationPlate plate) {
if (this.vehicleRegister.containsKey(plate.getRegCode())) {
return "The owner is: " + this.vehicleRegister.get(plate);
}
return null;
}


I thought the logic here would work because if the vehicleRegister contained the registrationcode string as a key it would return the string below. Is there a more clean-cut way of accessing the object in the hashmap?

Answer

Since the HashMap has RegistrationPlate as keys, you cannot expect to find a String that is the key. This means that you should do

this.vehicleRegister.containsKey(plate)

instead of

this.vehicleRegister.containsKey(plate.getRegCode())

However, you can call get() directly without calling containsKey() first:

public String get(RegistrationPlate plate) {
    return "The owner is: " + this.vehicleRegister.get(plate);
}

More importantly, you must override equals() and hashcode() in RegistrationPlate order to get the behavior that you wish. Otherwise, the default implementations will be used which return true only when the key is a reference to the exact same instance as the on stored in the HashMap. This is rarely the case. You typically want to compare the contents of the reference instead.