简体   繁体   中英

Keeping object in a map after removing it from a list

With the following code I loose my object in the Map after removing from the List , but I want to keep it in the Map :

ArrayList<object> myList= new ArrayList<>();
Map<String, ArrayList<object>> map = new HashMap<String, ArrayList<object>>();

myList.add(object);
map.put(key1,myList);
map.get(key1); // return [object]
myList.remove(get(index));
map.get(key1); // return []

You have to perform the remove on a copy of your list:

List<object> myList2 = new ArrayList<>(myList);
myList2.remove(get(index));

It seems like you're sending the object as it is from your list to the map, ie by reference. You might want to try to create a new object that has same values and send it to the map, instead of using the same object reference. This might be your problem.

ArrayList<object> myList = new ArrayList<>();
Map<String, ArrayList<object>> map = new HashMap<String, ArrayList<object>>();

myList.add(object);
map.put(key1, new ArrayList<>(myList));
map.get(key1);
myList.remove(get(index));
map.get(key1);

Read this topic could be useful Is Java “pass-by-reference” or “pass-by-value”?

When you have added the list then the list in the map and the individual list are having same memory address. So change in the individual list will also reflect in the change of list in map.

So you will have to create a copy of the list before adding it to the map.

Or the other solution is you can clone the map after the list has been added to the map.

It means that what you want to get done is getting the object without theobject leaving the list.

Simply use

 ArrayList.get(indexOfObjectToGet);

 //not 
 ArrayList.remove(indexOfObjectToGet);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM