我想用通用映射填充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
}
Run Code Online (Sandbox Code Playgroud)
为什么会这样?有什么我不明白的吗?
编辑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?
}
Run Code Online (Sandbox Code Playgroud)
我问这个的原因是因为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
}
Run Code Online (Sandbox Code Playgroud)
从文档中
当实际类型参数为?时,它代表某种未知类型.我们传递给add的任何参数都必须是这种未知类型的子类型.因为我们不知道它是什么类型,所以我们无法传递任何内容.唯一的例外是null,它是每种类型的成员.
所以,你只能添加
list.add(null);
请阅读Generics通配符的本教程
| 归档时间: |
|
| 查看次数: |
1954 次 |
| 最近记录: |