Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 11 down vote accepted

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));
share|improve this answer
1  
Yeah Agree nice use case.. I think I need to update my Ans.. Thank for your help. :-) – Ratan Mar 15 at 12:28
1  
Perfect time to vote for success.salesforce.com/ideaView?id=08730000000aDnYAAU so we can at least built our own HashSet<T> implementation. – Robert Sösemann Mar 16 at 8:58

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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