简体   繁体   中英

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.

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.

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>();
}

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.

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