有什么区别
List<Map<String, String>>
和
List<? extends Map<String, String>>
?
如果没有区别,使用有什么好处?扩展
?
最佳答案
不同之处在于,例如,一个
List<HashMap<String,String>>
是一个
List<? extends Map<String,String>>
但不是
List<Map<String,String>>
所以:
void withWilds( List<? extends Map<String,String>> foo ){}
void noWilds( List<Map<String,String>> foo ){}
void main( String[] args ){
List<HashMap<String,String>> myMap;
withWilds( myMap ); // Works
noWilds( myMap ); // Compiler error
}
你会认为 HashMap
的 List
应该是 Map
的 List
,但是有一个不这样做的充分理由:
假设你可以这样做:
List<HashMap<String,String>> hashMaps = new ArrayList<HashMap<String,String>>();
List<Map<String,String>> maps = hashMaps; // Won't compile,
// but imagine that it could
Map<String,String> aMap = Collections.singletonMap("foo","bar"); // Not a HashMap
maps.add( aMap ); // Perfectly legal (adding a Map to a List of Maps)
// But maps and hashMaps are the same object, so this should be the same as
hashMaps.add( aMap ); // Should be illegal (aMap is not a HashMap)
这就是为什么 HashMap
的 List
不应该是 Map
的 List
的原因。
关于java - List<Map<String, String>> vs List<?扩展 map <字符串,字符串>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9810445/