Case-Insensitive Maps?

How is it that describes seem to return case-insensitive maps? For instance, if I create a new custom setting, the following succeeds:

Map<String, SObjectField> fields1 = SObjectType.MySetting__c.fields.getMap();
system.assert(fields1.containsKey('Id'));

yet the following fails:

Map<String, SObjectField> fields2 = new Map<String, SObjectField>();
fields2.putAll(SObjectType.MySetting__c.fields.getMap());
system.assert(fields2.containsKey('Id'));

However, their keysets are the same, as the following will pass:

system.assertEquals(fields1.keySet(), fields2.keySet());

In both cases, the keyset is:

[“id”,”isdeleted”,”name”,”setupownerid”,”createddate”,”createdbyid”,”lastmodifieddate”,”lastmodifiedbyid”,”systemmodstamp”]

Clearly, only the lower case version of the string 'id' is in the map.

The same behavior seems to hold for Schema.getGlobalDescribe():

system.assert(Schema.getGlobalDescribe().containsKey('ACCOUNT'));

The above described behavior seems to violate the basics of how maps work in Apex. Is this in fact the same data structure? Can it be constructed by hand? It would potentially be useful, for instance, in parsing parameters on a page or REST service without needing to do some sort of loop through the keys with a case-insensitive comparison.

Answer

The docs outline the behaviour of the DescribeFieldResult map. See Accessing All Field Describe Results for an sObject

There’s a note saying:

The value type of this map is not a field describe result. Using the describe results would take too many system resources.
Instead, it is a map of tokens that you can use to find the appropriate field. After you determine the field, generate the describe
result for it.

It has the unique behaviour of:

  • It is dynamic, that is, it is generated at runtime on the fields for that sObject.
  • All field names are case insensitive.
  • The keys use namespaces as required.
  • The keys reflect whether the field is a custom object.

My understanding is that the keys are the tokens that have this unique behaviour, however in the second example, you’re explicitly instantiating a new Map<String, String> with the DescribeFieldResult map in it.

Attribution
Source : Link , Question Author : Adrian Larson , Answer Author : Nick Cook

Leave a Comment