说我有一个如何在Java中说“地图类<?>到列表<The class>”?
HashMap<?, List<?>> map = new HashMap<>();
map.put(String.class, new ArrayList<Long>());
将下面的代码编译。
不过,我想是因为ArrayList的不是字符串类型失败编译。
而且,我的通配符仅限于一些特定的接口(例如例外),所以我想我应该把那<? extends Exception>
地方。
我该如何达到上述目的?
试验例:
map.put(String.class, new ArrayList<String>()); //Fail because String is not an Exception
map.put(IOException.class, new ArrayList<FileNotFoundException>()); // Fail because FileNotFoundException is not an IOException even though it is a subclass of it
map.put(FileNotFoundException.class, new ArrayList<IOException>()); // I suppose I'm fine with this.
map.put(IllegalArgumentException.class, new ArrayList<IllegalArgumentException>()); // Succeed
map.put(NumberFormatException.class, new ArrayList<ServerException>()); // Fail again because the two classes don't match
map.put(ClientDecodingException.class, new ArrayList<ClientDecodingException.class>); // Succeed again since the map takes in a wildcard Exception
什么'地图,列表>'? –
不能做到:( – yshavit
@LuiggiMendoza这将需要''要声明的地方,然后你的地图只能包含类型的类/名单 - 你不能同时拥有T =字符串和T = IOException异常 –
yshavit