java – 我的方法泛型参数有什么问题
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 我的方法泛型参数有什么问题,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2666字,纯文字阅读大概需要4分钟。
内容图文
我想用通用映射填充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 generic
void 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 – 我的方法泛型参数有什么问题所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。