[SalesForce] apex Map.clear() vs new Map

So I have an map created

Map<String,Opportunity> mapIdOpp = new Map<String,Opportunity>();
// do something with the mapIdOpp

Now I want to reuse the map variable. Do I use

mapIdOpp.clear()

or

mapIdOpp= new Map<String,Opportunity>();

Best Answer

You can use either method, as they are semantically the same. However, as noted in the comments, sometimes you can only use one method or the other. For example, some maps are immutable and cannot be cleared (mostly those returned by system calls), and some variable are final and cannot be altered (mostly those specified by a developer). In some particularly rare cases, you might have a final immutable map, in which case you can't do anything with it at all.

So, it comes down to preference. I personally tend to create a new map when I need it rather than simply clearing the old one, which fits the paradigm of how I like to program. Others may prefer to simply clear the existing map. There's no "wrong" way to go about it, as long as you're consistent.

Related Topic