Reputation: 679
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.
Upvotes: 0
Views: 59
Reputation: 48258
Take a look to the inheritance tree in the collection
as you can see both classes can be implemented as a Map
so you can do:
Map<FooKey, FooValue> implementedMap = null;
if (b) {
implementedMap= new HashMap<FooKey, FooValue>();
} else {
implementedMap= new LinkedHashMap<FooKey, FooValue>();
}
Upvotes: 0
Reputation: 234715
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.
Upvotes: 1
Reputation: 48404
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>();
}
Upvotes: 3