Java 列表正在用最近的值替换所有旧值
我面临一个奇怪的问题,我没有找到任何解释,我将在代码中注释如下:Java 列表正在用最近的值替换所有旧值,java,android,arraylist,hashmap,Java,Android,Arraylist,Hashmap,我面临一个奇怪的问题,我没有找到任何解释,我将在代码中注释如下: final List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); Map<String,Object> map = new HashMap<String,Object>(); //for example payss ArrayList conta
final List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String,Object> map = new HashMap<String,Object>();
//for example payss ArrayList contains `A,B,C,D,E,F,G`
for (int i=0;i<payss.size();i++){
Bitmap contact_pic=pays_drapeaux.get(i);
drawable=new BitmapDrawable(contact_pic);
map.put("pays", payss.get(i).getNom());
Log.i("PAYS",payss.get(i).getNom()); //here it shows correctly the values one by one
map.put("drapeau",drawable);
list.add(map);
}
//here want to show what the list contains after setting it above
for (int i=0;i<list.size();i++){
Log.i("VALUES",list.get(i).values().toString()); //but here it shows G,G,G,G,G,G,G
}
final List=new ArrayList();
Map Map=newhashmap();
//例如,PayS ArrayList包含'A、B、C、D、E、F、G'`
对于(int i=0;i您只使用一个Map
对象,并将其多次添加到列表中。在第一个循环中,条目总是被覆盖(因为只有一个Map)。因此,很明显,只有最后的值仍然存在。您只使用一个映射
对象,并将其多次添加到列表中。在第一个循环中,条目总是被覆盖(因为只有一个映射).很明显,只有最后一个值仍然存在。昨晚我没有找到解决方案,但今天早上我刷新了:D.这是解决方案:
我必须在每个for循环中创建一个映射
for (int i=0;i<payss.size();i++){
Map<String,Object> map = new HashMap<String,Object>();
Bitmap contact_pic=pays_drapeaux.get(i);
drawable=new BitmapDrawable(contact_pic);
map.put("pays", payss.get(i).getNom());
map.put("drapeau",drawable);
Log.i("PAYS",payss.get(i).getNom());
list.add(map);
}
for(int i=0;i昨晚我没有找到解决方案,但今天早上我刷新了:D。以下是解决方案:
我必须在每个for循环中创建一个映射
for (int i=0;i<payss.size();i++){
Map<String,Object> map = new HashMap<String,Object>();
Bitmap contact_pic=pays_drapeaux.get(i);
drawable=new BitmapDrawable(contact_pic);
map.put("pays", payss.get(i).getNom());
map.put("drapeau",drawable);
Log.i("PAYS",payss.get(i).getNom());
list.add(map);
}
for(inti=0;iMap=newhashmap();
在for循环中写入上述行。这是一个非常愚蠢的错误;):)Map=newhashmap();
在for循环中写入上述行。这是一个非常愚蠢的错误;):)您必须在for循环中创建新映射
for (int i=0;i<payss.size();i++){
map = new HashMap<String, Object>();
Bitmap contact_pic=pays_drapeaux.get(i);
drawable=new BitmapDrawable(contact_pic);
map.put("pays", payss.get(i).getNom());
Log.i("PAYS",payss.get(i).getNom()); //here it shows correctly the values one by one
map.put("drapeau",drawable);
list.add(map);
}
for(int i=0;i必须在for循环中创建新映射
for (int i=0;i<payss.size();i++){
map = new HashMap<String, Object>();
Bitmap contact_pic=pays_drapeaux.get(i);
drawable=new BitmapDrawable(contact_pic);
map.put("pays", payss.get(i).getNom());
Log.i("PAYS",payss.get(i).getNom()); //here it shows correctly the values one by one
map.put("drapeau",drawable);
list.add(map);
}
for(int i=0;i你有理由,我只是在你写的时候发现了问题:D.我会接受你的答案;)。你有理由,我只是在你写的时候发现了问题:D.我会接受你的答案;)。一个让我醒了几个小时的错误:(!发生了…现在不会再发生了。cz nw u hv遇到了它:)一个让我醒了几个小时的错误:(!发生了…现在不会再发生了。cz nw u hv遇到了它。)