简体   繁体   English

嵌套hashmap中的java泛型/继承

[英]java generics/inheritance in nested hashmap

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 in time_id_police with a HashMap<Integer, Ambulance> . 显然HashMap<Integer, HashMap<Integer, Rescue>>是错误的,因为在time_id_police可以用HashMap<Integer, Ambulance>替换一个值。 A similar thing could be done if you replaced Rescue with ? extends Rescue 如果你用Rescue替换了Rescue ,可以做类似的事情? extends Rescue ? extends Rescue . ? extends Rescue

However, using ? extends 但是,使用? extends ? extends twice gives us something that wont break the type system. ? extends两次给我们一些不会打破类型系统的东西。

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

Most Java programmers prefer to use the more general Map in types rather than a specific implementation. 大多数Java程序员更喜欢在类型中使用更通用的Map而不是特定的实现。

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

Incidentally, if you change the body of your method to use the more concise ternary operator: 顺便提一下,如果更改方法的主体以使用更简洁的三元运算符:

   return a ? time_id_police : time_id_ambulance;

You get a slightly more helpful error message, as the compiler works out the type for you: 您会得到一个稍微有用的错误消息,因为编译器为您解决了类型:

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

Change your declarations of time_id_police and time_id_ambulance to 将time_id_police和time_id_ambulance的声明更改为

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

you might also want to declare them as Map instead of HashMap, this way if you ever decide to change the Map implementation you use, you'll only have to make a change in one place (where you instanciate your object) rather than in many places (where you use your object) 您可能还想将它们声明为Map而不是HashMap,这样如果您决定更改您使用的Map实现,您只需要在一个地方(您实例化您的对象)而不是在许多地方进行更改地方(你使用你的对象的地方)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM