javalinkedhashmapgeneric-method

Creating methods by specifying LinkedHashMaps with generic values as a parameter


Let's say I have a super class Car and my sub classes are Honda, Toyota, and Lexus.

I have 3 LinkedHashMaps using each sub class as the value:

LinkedHashMap<String, Honda> hondaModels = new LinkedHashMap<String, Honda>();
LinkedHashMap<String, Toyota> toyotaModels = new LinkedHashMap<String, Toyota>();
LinkedHashMap<String, Lexus> lexusModels = new LinkedHashMap<String, Lexus>();

What I am trying to achieve is something like this:

public <T> boolean checkModel(LinkedHashMap<String, <T>> lineup, String model) {
    if (lineup.containsKey(model)) {
        return true;
    }
    return false;
}

Is it possible for me to create a method by specifying LinkedHashMap with a generic value as a parameter so I don't have to repeat the same method for all 3 LinkedHashMaps?


Solution

  • If you only want to check if the map contains the key you can use the ? wildcard.

    public boolean checkModel(Map<String, ?> lineup, String model) {
        // trim any leading or trailing whitespace for the given vehicle model
        model = model.trim();
        if (lineup.containsKey(model)) {
            return true;
        }
        return false;
    }
    

    Now the method will accept any map as long as the key is a string.

    If you want to accept only maps that have a string as key and a car as object you can write Map<String, ? extends Car> instead. No need to use type parameters.