1

I have a HashMap that stores Id as key and an ArrayList as value. For a particular key, I want to get the corresponding ArrayList and manipulate one of the element of IEntity type inside that ArrayList.

My question is, as I update the property of element, would that be reflected in the ArrayList inside the HashMap as well? Or will I have to remove the list, replace that element in the list and again insert the list for that key to see the reflected value in the HashMap. I know that Java is pass by value, but its a little difficult to get my head around this scenario.

Below is the code I have. Thanks

ArrayList<IEntity> list = myMap.get(id);
Iterator<IEntity> itr = list.iterator();

        while(itr.hasNext()){               
            IEntity element = itr.next();
            if(element.checkSomeProperty() == false){
                element.setThatProperty(true);
// will above statement reflect the change in ArrayList stored in HashMap as well?
            }
        }

3 Answers 3

3

The element will be updated inside the HashMap as well. This is because it holds a reference to the ArrayList, which in turn contains the element. Even when the element is modified in some way, the map still points to the same list, which still holds and points to the same (now modified) element.

Sign up to request clarification or add additional context in comments.

Comments

1

Java uses reference variables for all variables, including the instance variables used inside the Map. Thus, you don't need to re-insert it (except if your map clones the objects, but the usual classes from the Collection framework do not).

Comments

0

Containers contain references to their elements, so changing the elements is immediately reflected in the collection as well. Because of this property, you should never mutate any object which is used as a key in a Map or Set.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.