[英]Map<String, List<? extends AbstractType>>
I was looking all around Stack Overflow but I don't know if that's possible but here is my question: 我一直在四处寻找Stack Overflow,但我不知道是否可行,但这是我的问题:
I have two types A
and B
extending from AbstractType
, then I want a Map
with both type of object inside like this: 我有两个从AbstractType
扩展的类型A
和B
,然后我想要一个Map
,里面有两种对象:
Map<String,List<? extends AbstractType>> map = new HashMap();
map.put("toto",new Arraylist<A>);
map.put("sacha",new Arraylist<B>);
List<A> a = (List<A>)map.get("toto");
I have a safety warning which is completely understandable, but that's the best way I found to make this work. 我有一个完全可以理解的安全警告,但这是我发现进行此工作的最佳方法。
The only safety option I found was to have two distinct lists, but I would rather prefer a map to avoid multiple if case. 我发现的唯一安全选择是有两个不同的列表,但是我宁愿选择一个映射来避免多个if情况。
I hope someone will have an idea. 我希望有人能有个主意。
You can also use instanceof
to always make sure that you don't get in some trouble. 您还可以使用instanceof
始终确保不会遇到麻烦。 Here is an example, you can modify it as per your requirements: 这是一个示例,您可以根据需要对其进行修改:
Map<String,List<? extends AbstractType>> map = new HashMap<>();
map.put("toto",new ArrayList<A>());
map.put("sacha",new ArrayList<B>());
List<? extends AbstractType> objList = (List<? extends AbstractType>) map.get("toto");
List<A> a = null;
List<B> b = null;
if(objList.size() > 0 && objList.get(0) instanceof A){
a = (List<A>) objList;
}else if (objList.size() > 0 && objList.get(0) instanceof B){
b = (List<B>) objList;
}
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.