2017-08-14 1 views
-1

j'ai un hashmap statique:ajouter hashmap à un autre

private static HashMap<String, byte[]> mDrawables = new HashMap<>(); 

par fil, je télécharger une image comme un octet [] et je veux ajouter ce nouveau hashmap à hashmap statique.

protected void onResult(String srv, HashMap<String, byte[]> drawables) { 
     super.onResult(srv, drawables); 
     mDrawables.putAll(drawables); 
} 

mais chaque fois invoqué putAll, toutes les informations sur mDrawables est effacé. comment pourrais-je ajouter une nouvelle clé de carte, valeur à statique une fois ??

+0

Avez-vous des clés en double? – Xvolks

+0

HashMap n'est pas sécurisé pour les threads. Vous devez le protéger des problèmes de synchronisation. – Xvolks

+0

@Xvolks, non chaque clé est et ID unique –

Répondre

1

Eh bien, accordint à 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 
*/ 

Ainsi, les mêmes touches sera remplacé. Vous pouvez utiliser Map#put() dans un cycle et le vérifier par vous-même comme suit:

for (Map.Entry<String, byte[]> entry : drawables.entrySet()) { 
    if (mDrawables.containsKey(entry.getKey())) { 
     // duplicate key is found 
    } else { 
     mDrawables.put(entry.getKey(), entry.getValue()); 
    } 
} 
+0

.votre code a une erreur attendue '; 'dans cette ligne 'pour (Map.Entry entry = drawables.entrySet()) {' –

+0

Désolé, l'avoir corrigé –