When a set collection contains objects such as Opportunities, what is used to determine uniqueness when the same Opportunity record is added to the collection a second time? I'm guessing that the system is considering the entire object (a hash?) so that any changes in the field values of a record results in the collection considering it as a new Opportunity record rather than replacing the previous one.
If I run this code the final count on the setOpportunities collection reveals that my assumption is correct:
Map<Id, Opportunity> mapOpportunities = new Map<Id, Opportunity>();
mapOpportunities.putAll([SELECT Id, Name, Type FROM Opportunity LIMIT 2]);
system.debug('Count of records in mapOpportunities = ' + mapOpportunities.size()); //size equals 2
Set<Opportunity> setOpportunities = new Set<Opportunity>();
for(Opportunity objOpportunity : mapOpportunities.values())
{
setOpportunities.add(objOpportunity);
}
system.debug('Count of records in setOpportunities = ' + setOpportunities.size()); //size equals 2
for(Opportunity objOpportunity : mapOpportunities.values())
{
setOpportunities.add(objOpportunity);
}
system.debug('Display setOpportunities records after being added again: ' + setOpportunities); //displays 2 records
system.debug('Count of records in setOpportunities after being added again = ' + setOpportunities.size()); //size equals 2
for(Opportunity objOpportunity : mapOpportunities.values())
{
//edit each opportunity and add it to the set again.
objOpportunity.Name = objOpportunity.Name + ' - Updated';
setOpportunities.add(objOpportunity);
}
system.debug('Count of records in setOpportunities after being updated and added = ' + setOpportunities.size()); //size equals 4
What is odd is what happens if I display the setOpportunities collection in the log. If I add:
system.debug('Display setOpportunities records after being updated and added: ' + setOpportunities); //displays 2 records (shouldn't this display 4 records??)
Only the two updated Opportunity records are displayed. This sent me in circles for a while because I was debugging an upsert issue by displaying the content of the set and it appeared as if there was only 2 records rather than the actual 4.
Am I crazy? Any thoughts on why it only displays the 2?