2

I am trying to remove duplicates from a List of Custom Objects.

This is what I am doing:

Set<CustomObject> mySet = new Set<CustomObject>();
mySet.addAll(originalList); //OriginalList contains duplicate Custom Objects.
System.debug(mySet.size()); //This always prints the same size of the original list

I don't know what is wrong happening here, When I see the list of items using debug there are clearly two Objects with same details.

Anything am I missing??

2
  • 1
    This may help you understand what's going on.
    – BarCotter
    Commented Mar 12, 2015 at 15:36
  • 2
    @BarCotter , Thanks for the link. I ended up adding the implementation for equals and hashCode method and now it is working fine.
    – javanoob
    Commented Mar 12, 2015 at 16:46

1 Answer 1

1

The Ids of records of that CustomObject are different. So the values in the set are different(each record is unique) and that's why they are not de-duplicated. If you want to use the Set based approach, clone each record and add it to the Set.

Set mySet = new Set();

for(CustomObject co : originalList) { mySet.add(co.clone()); }

//Check the size

1
  • Just tried it and I am still seeing the same size.. Do you think I should provide implementation for equals and hashCode method for my Custom Object??
    – javanoob
    Commented Mar 12, 2015 at 16:01

You must log in to answer this question.

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