Domanda

Ho un concurentthashmap nel formato sottostante:

ConcurrentHashMap<String,ConcurrentHashMap<String,ArrayList>>
.

Ora in questa mappa, voglio rimuovere un particolare valore nell'elenco Array.Can Guida a qualcuno con questo.

Edit1: Ho una mappa <"Pacchetto1" -> <"NR1", [PR1, PR2] >> <"Pacchetto1" -> <"NR2", [PR1, PR2] >>

Ora quando rimuovo Map.get ("Packet1"). Ottieni ("NR1"). Rimuovi ("PR2") Rimuove PR2 da NR1 che NR2.isnt dovrebbe rimuovere solo da NR1.AM che faccio qualcosa di sbagliatoqui. Aggiornami,

P.S: Sono aggiornato la mappa per la seconda volta per lo stesso pacchetto chiave1 con entrambi i valori NR1 che NR2

È stato utile?

Soluzione

You've made a mistake setting up the map. When you added the lists for NR1 and NR2, you used the same list object. Your map now contains two references to that list. When you remove the element from the NR1 list, you're removing it from the same list that is visible under NR2.

The solution is to fix your code, so that when you insert a list into the map, you insert a different list for each key.

You say in a comment on JB's post that you didn't do this. The fact is, you did do this. You just haven't realised it yet!

Altri suggerimenti

map.get("key1").get("key2").remove(particularValue);

Each time I see such a structure, I wonder why a Key class, containing the two String keys and implementing equals and hashCode properly, is not used instead. The map would then become a Map<Key, List<Foo>>.

And should even be implemented (using Guava) using a MultiMap<Key, Foo>, which would make it easier to use and maintain.

You simply do

// Get hold of the map containing the list
Map<String, ArrayList> innerMap = yourMap.get("primaryKey");

// Get hold of the list
ArrayList listToRemoveFrom = innerMap.get("secondaryKey");

// Remove from the list
listToRemoveFrom.remove(objectToRemove);

or, in a single line:

yourMap.get("yourPrimaryKey").get("yourSecondaryKey").remove(objectToRemove);

As Jim Garrison points out, unless you're certain that your map contains "yourPrimaryKey", and your inner map contains "yourSecondaryKey" you need to check for nulls in each case.


As a side-note: I encourage you to use generics all the way through, and specify which element type your ArrayList will contain by declaring the map as

ConcurrentHashMap<String,ConcurrentHashMap<String,ArrayList<SomeType>>>
                                                           ^^^^^^^^^^

Or, even better, code against interfaces if possible, and write

Map<String,Map<String,List<SomeType>>>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top