سؤال

لدي concurrenthmap بالتنسيق أدناه: giveacodicetagpre.

الآن في هذه الخريطة، أريد إزالة قيمة معينة في قائمة الصفيف. هل يجسد أي شخص مع هذا.

Edit1: لدي خريطة <"Packet1" -> > <"Packet1" -> <"NR2"، [PR1، PR2] >>

الآن عندما أزيل MAP.GET ("Packet1"). احصل ("NR1"). إزالة ("PR2"). يزيل ("PR2") يزيل PR2 من كل من NR1 و NR2.isNT يجب إزالته فقط من NR1.am أفعل أي شيء خاطئhere.plz تحديث لي،

p.s: أنا تحديث الخريطة للمرة الثانية لنفس الحزمة الرئيسية 1 مع كلا القيم NR1 و NR2

هل كانت مفيدة؟

المحلول

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!

نصائح أخرى

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>>>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top