2

SetA.removeAll(setB) removes the value even from map it is fetched from.

Map<String,set<String>> MapOne = new Map<String,set<String>>();

set<String> one= new set<String>();

set<String> two = new set<String>();

set<String> three = new set<String>();


one.add('One');
one.add('Two');
MapOne.put('A',one);

two = MapOne.get('A');
three.add('One');
three.add('Four');
three.add('Five');

system.debug('value is-->' +MapOne);
two.removeAll(three);
system.debug('value is-->' +MapOne);

After removeAll even the value from Map is removed. Can somebody explain why it is modifying the original map also.

1
  • 2
    That is because all values are getting passed by reference.
    – abhi
    Oct 27, 2016 at 17:18

1 Answer 1

5

Apex collections are always passed by reference meaning that it is just a pointer to the original collection. If you want to create a new instance of a collection that can be independently modified you will want to use the clone() method on the collection. More information is available at https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_set.htm

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .