[英]2 different possibles types for 1 variable
I want to do exactly this in Java: 我想在Java中完全做到这一点:
boolean b;
if (b) {
//I want that a variable "imp" be of type HashMap
} else {
//I whant that a variable "imp" be of type LinkedHashMap
}
HashMap
and LinkedHashMap
are implementation of interface map. HashMap
和LinkedHashMap
是接口映射的实现。
I think use a tuple (HashMap, LinkedHashMap)
but this dirties so much of the code. 我认为使用元组
(HashMap, LinkedHashMap)
但这会弄脏很多代码。
Just declare imp
as Map
, parametrized with your desired type parameters, and assign it with the concrete type. 只需将
imp
声明为Map
,并使用所需的类型参数对其进行参数化,然后将其分配为具体类型。
Both HashMap
and LinkedHashMap
are Map
s and can be referenced as such. HashMap
和LinkedHashMap
都是Map
,可以这样引用。
Map<MyKey, MyValue> imp = null;
if (b) {
imp = new HashMap<MyKey, MyValue>();
} else {
imp = new LinkedHashMap<MyKey, MyValue>();
}
I'd shoot for 我会为
Map<MyKey, MyValue> imp = b ? new HashMap<>() : new LinkedHashMap<>();
Note the use of the diamond operator : there's no need to spell the generics out long-hand. 请注意使用Diamond运算符 :无需长期拼写泛型。
Using the ternary conditional operator in this way means that imp
is never in an undefined state between declaration and initialisation. 以这种方式使用三元条件运算符意味着
imp
在声明和初始化之间永远不会处于未定义状态。
Take a look to the inheritance tree in the collection 看一下集合中的继承树
as you can see both classes can be implemented as a Map 如您所见,两个类都可以实现为Map
so you can do: 因此,您可以执行以下操作:
Map<FooKey, FooValue> implementedMap = null;
if (b) {
implementedMap= new HashMap<FooKey, FooValue>();
} else {
implementedMap= new LinkedHashMap<FooKey, FooValue>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.