列表&lt;地图&lt;字符串,字符串&gt;&gt;vs 列表<?extends Map<String, String>> [英] List&lt;Map&lt;String, String&gt;&gt; vs List&lt;? extends Map&lt;String, String&gt;&gt;

查看:41
本文介绍了列表&lt;地图&lt;字符串,字符串&gt;&gt;vs 列表<?extends Map<String, String>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别吗

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
}

你会认为 HashMapList 应该是 MapList,但有一个为什么不是:

You would think a List of HashMaps should be a List of Maps, but there's a good reason why it isn't:

假设你可以:

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)

所以这就是为什么 HashMapList 不应该是 MapList 的原因.

So this is why a List of HashMaps shouldn't be a List of Maps.

这篇关于列表&lt;地图&lt;字符串,字符串&gt;&gt;vs 列表<?extends Map<String, String>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆