列表< Map< String,String>> vs List&lt ;?扩展Map< String,String&am

编程入门 行业动态 更新时间:2024-10-20 21:10:26
本文介绍了列表< Map< String,String>> vs List&lt ;?扩展Map< String,String>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

List< Map< String,String>>

列表与LT ;?扩展Map< String,String>>

如果没有差别,使用有什么好处?扩展?

解决方案

不同之处在于,例如,一个

List< HashMap< String,String>>

是一个

列表与LT ;?扩展Map< String,String>>

但不是

列表与LT;地图; LT;字符串,字符串>>

所以:

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); //编译器错误}

你会认为 List HashMap s应该是 List Map s,但是有一个很好的理由不是:

假设你可以这样做:

列表与LT; HashMap中<字符串,字符串>> hashMaps = new ArrayList< HashMap< String,String>>(); 列表< Map< String,String>> maps = hashMaps; //不会编译, //但想象它可以 Map< String,String> aMap = Collections.singletonMap(foo,bar); //不是HashMap maps.add(aMap); //完全合法(将地图添加到地图列表中) //但是maps和hashMaps是同一个对象,所以这应该与 hashMaps相同。添加(aMap); //应该是非法的(aMap不是HashMap)

所以这就是为什么一个<$ c $ HashMap s的列表不应该是列表 of Map s。

Is there any difference between

List<Map<String, String>>

and

List<? extends Map<String, String>>

?

If there is no difference, what is the benefit of using ? extends?

解决方案

The difference is that, for example, a

List<HashMap<String,String>>

is a

List<? extends Map<String,String>>

but not a

List<Map<String,String>>

So:

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 }

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

Suppose you could do:

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)

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

更多推荐

列表&lt; Map&lt; String,String&gt;&gt; vs List&lt ;?扩展Map&

本文发布于:2023-11-02 17:27:57,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   lt   amp   Map   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!