1

I am confused by my test results:

Set<opportunity> setOpp = new Set<opportunity>();
Opportunity opp = [select Id,CloseMonthText__c from Opportunity where     id='0067000000hqu5X'];
for(integer i=0;i<10;i++){
    opp.CloseMonthText__c='A'+i;
    setOpp.add(opp);
}
System.debug('SetOpp: '+setOpp);
System.debug('size: '+setOpp.size());

For(opportunity o:setOpp){
    System.debug(o);
}

The output I get is something like this:

SetOpp: {Opportunity:{Id=XXXX,CloseMonthText__c=A9}}

Size: 10

Opportunity:{Id=XXXX,CloseMonthText__c=A9

Opportunity:{Id=XXXX,CloseMonthText__c=A9

Opportunity:{Id=XXXX,CloseMonthText__c=A9

Opportunity:{Id=XXXX,CloseMonthText__c=A9

Opportunity:{Id=XXXX,CloseMonthText__c=A9

Opportunity:{Id=XXXX,CloseMonthText__c=A9

Opportunity:{Id=XXXX,CloseMonthText__c=A9

Opportunity:{Id=XXXX,CloseMonthText__c=A9

Opportunity:{Id=XXXX,CloseMonthText__c=A9

Opportunity:{Id=XXXX,CloseMonthText__c=A9

I know that set detect duplication of SObject by checking all the fields of the record. I think Set stores a reference to the actual instance. In the for loop it's also changing the referenced value of set. How come the set size is 10? Can anyone explain the output?

enter image description here

4
  • @AdrianLarson man, I still remember you marked my previous post as duplicate but it actually wasn't a duplicate. If you can't answer can you leave this to other might be able to help?
    – sfdcnoob
    Sep 23, 2015 at 23:07
  • 1
    Modified my opportunity object to include CloseMonthText__c. Executed code in DevConsole anonymous window and could not reproduce. I got 3 debug outputs as one would expect. Sep 23, 2015 at 23:36
  • I was also not able to reproduce your results.
    – martin
    Sep 24, 2015 at 1:11
  • 2
    @sfdcnoob Marking duplicate questions as such is a core feature of this network and is part of what makes it work so well. In this case I don't think it is a duplicate, though the answer linked to does explain the behaviour you're seeing.
    – Matt Lacey
    Sep 24, 2015 at 4:13

1 Answer 1

4

Every time you change a field on an sObject you are changing its hash value. It is this hash value that is used as a key in the Set to determine if a new record is being added or an existing one updated. The Set will accept 10 adds for the same Opportunity as the hash will be different every time after changing the field.

There is still only one Opportunity sObject stored in memory, with 10 references to it from the Set.

1

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