Java泛型,通配符的嵌套集合 [英] Java generics, nested collection of wildcard
本文介绍了Java泛型,通配符的嵌套集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个编译(1.6)
List< ;?扩展对象> l = new ArrayList< Date>();
但这不是
列表与LT;名单,LT ;?扩展对象>> ll = new ArrayList< List< Date>>();
错误为
类型不匹配:无法从ArrayList转换< List< Date>>列出<列表<扩展对象>>
有人可以解释为什么吗?
谢谢
编辑:为后续编辑
解决方案
因为它会破坏类型安全:
List< List< Object>> lo = new ArrayList< List< Object>>();
列表<列表< ;?扩展对象>> ll = lo;
列表< String> ls = new ArrayList< String>();
ll.add(ls);
lo.get(0).add(new Object());
String s = ls.get(0); //将一个普通的Object实例赋值给一个String引用
This compiles (1.6)
List<? extends Object> l = new ArrayList<Date>();
But this does not
List<List<? extends Object>> ll = new ArrayList<List<Date>>();
with the error of
Type mismatch: cannot convert from ArrayList<List<Date>> to List<List<? extends Object>>
Could someone explain why? Thanks
EDIT: edited for being consequent
解决方案
Because it would break type safety:
List<List<Object>> lo = new ArrayList<List<Object>>();
List<List<? extends Object>> ll = lo;
List<String> ls = new ArrayList<String>();
ll.add(ls);
lo.get(0).add(new Object());
String s = ls.get(0); // assigns a plain Object instance to a String reference
这篇关于Java泛型,通配符的嵌套集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文