NahuelBrandan
NahuelBrandan

Reputation: 679

2 different possibles types for 1 variable

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

Answers (3)

Take a look to the inheritance tree in the collection

enter image description here

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

Bathsheba
Bathsheba

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

Mena
Mena

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 Maps 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

Related Questions