列表< Map< String,String>> vs List< ;?扩展Map< String,String>> [英] List<Map<String, String>> vs List<? extends Map<String, String>>
本文介绍了列表< Map< String,String>> vs List< ;?扩展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 HashMap
s should be a List
of Map
s, 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 HashMap
s shouldn't be a List
of Map
s.
这篇关于列表< Map< String,String>> vs List< ;?扩展Map< String,String>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文