I want to do exactly this in 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.
I think use a tuple (HashMap, LinkedHashMap)
but this dirties so much of the code.
Just declare imp
as Map
, parametrized with your desired type parameters, and assign it with the concrete type.
Both HashMap
and LinkedHashMap
are Map
s and can be referenced as such.
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.
Using the ternary conditional operator in this way means that imp
is never in an undefined state between declaration and initialisation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.