8

If you take a look into this issue

Duplicate id in list: 003E000001YDH1jIAH

I have provide an answer of using set<Sobject> instead using list<Sobject>

i.e.

if( !contacts.values().isEmpty() ){
  set<Contact> setContacts = new set<Contact>();
  for( Contact objCon : contacts.values() ){
    if(!setContacts.contains(objCon)){
        setContacts.add( objCon );
    }
  }
 update new list<Contact>(setContacts);
}

even if(!setContacts.contains(objCon)) is not needed

if( !contacts.values().isEmpty() ){
  set<Contact> setContacts = new set<Contact>();
  for( Contact objCon : contacts.values() ){
        setContacts.add( objCon );
  }
 update new list<Contact>(setContacts);
}

So is there any condition/use case where this answer might fail?

1 Answer 1

16

No. Any field variation will cause the records to hash differently, even if they have the same Id. This is why Map<Id, SObject> is preferable.

Id commonId = '001000000000000AAA';
Account a = new Account(Id=commonId, Name='A');
Account b = new Account(Id=commonId, Name='B');
Set<Account> records = new Set<Account> { a, b };

system.assertEquals(2, records.size());

system.assertNotEquals(system.hashCode(a), system.hashCode(b));
2

You must log in to answer this question.

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