Android 将hashmap添加到另一个

Android 将hashmap添加到另一个,android,hashmap,Android,Hashmap,我有一个静态哈希映射: private static HashMap<String, byte[]> mDrawables = new HashMap<>(); private static HashMap mDrawables=new HashMap(); 通过线程,我下载了一个字节为[]的图像,我想将这个新的hashmap添加到静态hashmap中 protected void onResult(String srv, HashMap<String, byt

我有一个静态哈希映射:

private static HashMap<String, byte[]> mDrawables = new HashMap<>();
private static HashMap mDrawables=new HashMap();
通过线程,我下载了一个字节为[]的图像,我想将这个新的hashmap添加到静态hashmap中

protected void onResult(String srv, HashMap<String, byte[]> drawables) {
      super.onResult(srv, drawables);
      mDrawables.putAll(drawables);
}
protectedvoid onResult(字符串srv、HashMap可绘制文件){
super.onResult(srv,可抽出式);
mDrawables.putAll(可提取);
}
但每次调用putAll时,mDrawables上的所有信息都会被清除。
如何将新的映射键、值添加到静态一次???

好吧,根据JavaDoc:

/**
 * Copies all of the mappings from the specified map to this map.
 * These mappings will replace any mappings that this map had for
 * any of the keys currently in the specified map.
 *
 * @param m mappings to be stored in this map
 * @throws NullPointerException if the specified map is null
 */
因此,相同的钥匙将被替换。您可以在一个循环中使用
Map#put()
,然后自己进行如下检查:

for (Map.Entry<String, byte[]> entry : drawables.entrySet()) {
    if (mDrawables.containsKey(entry.getKey())) {
        // duplicate key is found
    } else {
        mDrawables.put(entry.getKey(), entry.getValue());
    }
}
for(Map.Entry:drawables.entrySet()){
if(mDrawables.containsKey(entry.getKey())){
//找到重复的密钥
}否则{
mDrawables.put(entry.getKey(),entry.getValue());
}
}

是否有重复的密钥?HashMap不是线程安全的。您必须保护它不受计时问题的影响。@Xvolks,没有每个键都是唯一的id1-是否有其他线程同时访问
mDrawables
?2-添加日志以显示添加新条目前后hashmap的大小:
Log.i(“HASH”,“size before=“+mDrawables.size());mDrawables.putAll(可提取);Log.i(“HASH”,“size after=“+mDrawables.size())并查看在Logcat中得到的结果,,,即使有重复的密钥,它们也应该被替换而不是删除。因此,哈希值没有理由为空,除非它已经为空,或者其他线程正在同时使用/删除条目。我已调试,每次只添加一个映射。您的代码预期有错误“;”在这一行中,
for(Map.Entry=drawables.entrySet()){
对不起,修复了它