我想用通用映射填充List,但我的代码不能编译.我已经为这个问题准备了最简单的例子.在上面的注释问题中,我把错误放在下面的行中.
voID populateList(List<? extends Map<String,?>> List) { List.clear(); HashMap<String, ?> map; map = new HashMap<String,String>(); //The method put(String, capture#2-of ?) in the type HashMap<String,capture#2-of ?> is not applicable for the arguments (String, String) map.put("key", "value"); // this line does not compile // The method add(capture#3-of ? extends Map<String,?>) in the type List<capture#3-of ? extends Map<String,?>> is not applicable for the arguments (HashMap<String,capture#5-of ?>) List.add(map); //This line does not compile}
为什么会这样?有什么我不明白的吗?
编辑1
根据下面的一个答案,他指出了?代表未知类型而不是Object的后代.这是一个有效的观点.而且,在方法内部我知道进入map的类型,所以我相应地修改了我的简单代码.
voID populateList(List<? extends Map<String,?>> List) { List.clear(); HashMap<String, String> map; //kNown types map = new HashMap<String,String>(); map.put("key", "value"); // this line Now compiles // The method add(capture#3-of ? extends Map<String,?>) in the type List<capture#3-of ? extends Map<String,?>> is not applicable for the arguments (HashMap<String,capture#5-of ?>) List.add(map); //This line STILL does not compile. Why is that?}
我问这个的原因是因为androID SDK的方法形式需要这样的列表,因为它似乎无法填充这样的列表.怎么做到这一点?类型转换?
编辑2
由于有几个改变我的签名的提议,我将补充说我不能这样做. Basicaly,我想填充SimpleExpandablalistadapter的列表.
voID test() { ExpandableListVIEw expandableListVIEw.setAdapter(new ArrayAdapterRetailStore(this, R.layout.List_item_retail_store, retailStores)); List<? extends Map<String, ?>> groupData= new ArrayList<HashMap<String,String>>(); populateGroup(groupData) // child data ommited for simplicity expandableListVIEw.setAdapter( new Simpleexpandablelistadapter( this, groupdata, R.layout.List_group, new String[] {"GroupKey"}, new int[] {R.ID.tvGroupText}, childData, R.layout.List_item_child, new String[] {"ChildKey"}, new int[] {R.ID.tvChilText}));}// I want populateGroupData() to be genericvoID populateGroupData(List<? extends Map<String,?>> groupData) { groupData.clear(); HashMap<String,String> map; map = new HashMap<String,String>(); map.put("key", "value"); groupData.add(map); // does not compile }
解决方法:
从文档中
When the actual type parameter is ?, it stands for some unkNown type. Any parameter we pass to add would have to be a subtype of this unkNown type. Since we don’t kNow what type that is, we cannot pass anything in. The sole exception is null, which is a member of every type.
所以,你只能添加
List.add(NulL);
请在Generics Wildcards阅读本教程
总结以上是内存溢出为你收集整理的java – 我的方法泛型参数有什么问题全部内容,希望文章能够帮你解决java – 我的方法泛型参数有什么问题所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)