0

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?

phamous
  • 177
  • 10
  • 2
    Side note: Unless there's something peculiar about all Toyotas (and other other brands) that requires its own class, better to just have a `brand` field in `Car` than to have subclasses. Perhaps `InternalCombustionCar`, `HybridCar` and `ElectricCar` may have been better choices? Or even no subclasses, just `Map hondaModels = ...` appropriately populated is what you want. – Bohemian Nov 23 '21 at 01:37
  • Thanks for the thought, it was just meant to be a quick example to illustrate how I can check if a map contains a key, regardless of what the map is, as long as the key is a string. – phamous Nov 23 '21 at 02:22

1 Answers1

6

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.

magicmn
  • 1,787
  • 7
  • 15