if i have two hashmaps, of types
HashMap<Integer, HashMap<Integer, Police>> time_id_police;
HashMap<Integer, HashMap<Integer, Ambulance>> time_id_ambulance;
where Police and Ambulance both extend Rescue, how can i have a method like
HashMap<Integer, HashMap<Integer, Rescue>> getRescue(){
if (a) return time_id_police;
else return time_id_ambulance;
}
neither this, nor changing the return type to
HashMap<Integer, HashMap<Integer, ? extends Rescue>>
seems to work.
thanks a lot.
Clearly
HashMap<Integer, HashMap<Integer, Rescue>>is wrong because then a value could be replaced intime_id_policewith aHashMap<Integer, Ambulance>. A similar thing could be done if you replacedRescuewith? extends Rescue.However, using
? extendstwice gives us something that wont break the type system.Most Java programmers prefer to use the more general
Mapin types rather than a specific implementation.Incidentally, if you change the body of your method to use the more concise ternary operator:
You get a slightly more helpful error message, as the compiler works out the type for you: