gpt4 book ai didi

java - 1 个变量有 2 种不同的可能类型

转载 作者:行者123 更新时间:2023-12-01 18:03:34 24 4
gpt4 key购买 nike

我想在 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
}

HashMapLinkedHashMap是接口(interface)map的实现。

我认为使用元组(HashMap, LinkedHashMap)但这会弄脏很多代码。

最佳答案

只需将 imp 声明为 Map,使用所需的类型参数进行参数化,然后为其分配具体类型。

HashMapLinkedHashMap 都是 Map,并且可以这样引用。

Map<MyKey, MyValue> imp = null;
if (b) {
imp = new HashMap<MyKey, MyValue>();
} else {
imp = new LinkedHashMap<MyKey, MyValue>();
}

关于java - 1 个变量有 2 种不同的可能类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38744557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com