リスト > リスト > 質問する

リスト > リスト > 質問する

何か違いはありますか?

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
}

Listsのa は sのHashMapa であるべきだと思われるでしょうが、そうではないのには十分な理由があります。ListMap

次のようなことができるとします:

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 Listof HashMaps は a Listof Maps であってはならないのです。

おすすめ記事