I have a Set
which appears to have duplicate values. Here is the pseudocode:
list<SOBject__c> list1 = [select id from SObject__c where blah blah blah];
list<SObject__c> list2 = [select id from SObject__c where blah blah blah];
list<SObject__c> list3 = [select id from SObject__c where blah blah blah];
set<SObject__c> combinedSet = new set<SObject__c>();
combinedSet.addall(list1);
combinedSet.addall(list2);
combinedSet.addall(list3);
A few of the items in list1
and list3
are identical. My expectation is that when I add all three lists to the set, that addall()
will ignore any element that's already present in the set. However, when I iterate through combinedSet
and look at SObject__c.Name
, the items that overlap in list1
and list3
are in the set twice. (I do not have records with the same SObject__c.Name
.)
How is this possible?
EDIT: Since there have been questions, I decided to be a bit more verbose and share most of the actual code. I'm going to share the part of the code that I believe is relevant. I have an object called Show__c
. I'm querying against Show__c
three times with three different conditions. That gives me three lists. But there are some records in Show__c
for which two of the conditions are true, so two of the three lists overlap. That's why I use a set to remove the duplicates.
list<Show__c> list1 = [select id from Show__c where condition A];
list<Show__c> list2 = [select id from Show__c where condition B];
list<Show__c> list3 = [select id from Show__c where condition C];
set<Show__c> allShows = new set<Show__c>();
allShows.addall(list1);
allShows.addall(list2);
allShows.addall(list3);
Next I have another object called Hop__c
which has two fields, a Master-Detail with Show__c
and a Date. I insert the Show__c
records from the set into Hop__c
.
list<Hop__c> toInsert = new list<Hop__c>();
for (Show__c s : allShows) {
Hop__c b = new Hop__c();
b.Show__c = s.id;
b.Week_Starting__c = date.today().adddays(1);
toInsert.add(b);
}
if (!toInsert.isempty()) insert toInsert;
After this runs (this is a Scheduled Apex), I look in Hop__c
(which was previously empty) by generating a "Shows with Hops" report from within the SFDC UI. In the report I see the several instances of the same Show__c
, which should not happen. When I run each individual query that generates the lists, I see some of the same records in list1
and list3
, and those same records show up as duplicates in Hop__c
. It's as if the set is storing duplicates.
Name
would be null in your example. Just shooting for the moon here but sObjects are considered unique base on field comparisions. It could be possible that with formula fields on the object or something else between list 1 and list 3 being executed that something on them made them different. Is it always the same IDs? Did you check to see if the ID's were the same and not the name? – Eric Feb 7 '15 at 3:29