何か違いはありますか?
List<Map<String, String>>
そして
List<? extends Map<String, String>>
?
違いがない場合、 を使用する利点は何ですか? extends
?
ベストアンサー1
違いは、例えば、
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
}
List
sのa は sのHashMap
a であるべきだと思われるでしょうが、そうではないのには十分な理由があります。List
Map
次のようなことができるとします:
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)
したがって、a List
of HashMap
s は a List
of Map
s であってはならないのです。