Java generics / inheritance in nested hashmap

if I have two hashmaps, types

HashMap<Integer, HashMap<Integer, Police>> time_id_police;  
HashMap<Integer, HashMap<Integer, Ambulance>> time_id_ambulance;

where the police and the ambulance prolong the rescue, how can I get a method like

HashMap<Integer, HashMap<Integer, Rescue>> getRescue(){
   if (a) return time_id_police;
   else return time_id_ambulance;
}

neither this nor change of return type to

HashMap<Integer, HashMap<Integer, ? extends Rescue>> 

seems to work.

Many thanks.

+3
source share
2 answers

It is clear that this HashMap<Integer, HashMap<Integer, Rescue>>is not true, because then the value can be replaced time_id_policeby HashMap<Integer, Ambulance>. A similar thing can be done if you replaced Rescuewith ? extends Rescue.

However, using ? extendstwice gives us something that does not violate the type system.

HashMap<Integer, ? extends HashMap<Integer, ? extends Rescue>> getRescue() {

Java Map, .

Map<Integer, ? extends Map<Integer, ? extends Rescue>> getRescue() {

, :

   return a ? time_id_police : time_id_ambulance;

, :

R.java:18: incompatible types
found   : java.util.HashMap<java.lang.Integer,capture of ? extends java.util.HashMap<java.lang.Integer,? extends Rescue>>
required: java.util.HashMap<java.lang.Integer,java.util.HashMap<java.lang.Integer,Rescue>>
   return a ? time_id_police : time_id_ambulance;
        ^
1 error
+3

time_id_police time_id_ambulance

HashMap<Integer, HashMap<Integer, Rescue>> time_id_police;
HashMap<Integer, HashMap<Integer, Rescue>> time_id_ambulance;

Map HashMap, , - , ( ) ( )

Map<Integer, Map<Integer, Rescue>> time_id_police = new HashMap<Integer, HashMap<Integer, Rescue>>();
0

Source: https://habr.com/ru/post/1716214/


All Articles