-1

I have a HashMap from this I get one of the ArrayList's using the following:

ArrayList details = map.get(index);

This works perfectly, but when I use remove on the ArrayList details, it causes the same field to be removed from the HashMap.

I have printed out the values for the HashMap and ArrayList before and after the remove, this shows the data is correctkly removed from the ArrayList, but the HashMap is also affected by this remove.

Why?

  • 3
    `ArrayList details = map.get(index)` doesn't make a copy; it refers to the same basic object in memory. – Louis Wasserman Mar 24 '15 at 02:30
  • 1
    Can you post the whole relevant code? – alainlompo Mar 24 '15 at 02:30
  • What @LouisWasserman said. If you don't want operations on the `List` to affect the contents of the `Map`, make a defensive copy: `List> details = new ArrayList<>(map.get(index));`. Also you should not use raw types. – ach Mar 24 '15 at 02:38
  • I have looked at other sites and would like to try and understand why, if I create, `HashMap filteredMap = new HashMap<>(oiginalMap);`, which I thought would create a defensive copy. I assume it does not as when I create an ArrayList from the filteredMap, it still emoves from the original. – Stuart68 Mar 25 '15 at 02:06

1 Answers1

0

As Louis Wasserman said, manipulating 'details' will also affect the one in the map as they are both referring to one and the same ArrayList.

You will need to clone the ArrayList AND its contents if you want to manipulate them without affecting the one from the map.

You may refer to this stackoverflow question on how to do this.

Goodluck.

Community
  • 1
  • 1
ochiboy
  • 85
  • 1
  • 7