Home > Software design >  Creating methods by specifying LinkedHashMaps with generic values as a parameter
Creating methods by specifying LinkedHashMaps with generic values as a parameter

Time:11-23

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) {
    // trim any leading or trailing whitespace for the given vehicle model
    model = model.trim();
    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?

CodePudding user response:

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.

CodePudding user response:

The method you have in your question will work once you fix the syntax error.

If you want to restrict it to checking Maps of Cars you can declare the function as:

public <T extends Car> boolean checkModel(LinkedHashMap<String, T> lineup, String model) {
...
}
  • Related