3
Set<Id> testIds = new Set<Id>();
testIds.add(null);

system.debug('testIds are ' + testIds);

system.debug('Size of the set is ' + testIds.size());
system.debug('isEmpty result is ' + testIds.isEmpty());

Here's what I get out of these debugs:

testIds are {null}

Size of the set is 1

isEmpty result is false

Perhaps I am incorrect but I thought that adding null to a Set<Id> should not add anything to the set. Instead it's converting the null to what looks like a String?

Is this the expected behavior or was there a change in APEX?

5

What you have observed is expected behavior: null is a valid collection element, and containing it makes the collection non-empty.

  • Okay, thank you, I suppose I was completely wrong on this one. – Arthlete Apr 18 '19 at 17:59
  • 1
    It happens to the best of us. :) – Adrian Larson Apr 18 '19 at 17:59
  • So then that means that I should perform an if statement before adding a field to this set. For example if (myObj__c.someField__c != null) { myIds.add(myObj__c.someField__c); } otherwise it will think that the set holds an Id value. – Arthlete Apr 18 '19 at 18:02
  • 1
    More efficient to just remove it once at the end if you are using a set. – Adrian Larson Apr 18 '19 at 18:04
  • Yeah absolutely, but I swear I didn't have to do this before. My memory is playing tricks on me. – Arthlete Apr 18 '19 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.