+ Start a Discussion
unidhaunidha 

Set Decimal - Why it print only one element while it contains two elements?

I found this by accident while trying to implement user requirement.I code this in Apex Execute Anonymous:
 
List<Decimal> lstDecimal =new List<Decimal>{0.0,0.00};
Set<Decimal> setDecimal =new Set<Decimal>(lstDecimal);
system.debug('@NUR ..'+setDecimal+ ', '+setDecimal.size());

But the result come out as below:
19:03:56:076 USER_DEBUG [3]|DEBUG|@NUR ..{0.0}, 2
Anyone knows why it only print {0.0}  instead of {0.0,0.00} ? The size clearly state it has two elements.Is it Salesforce bug?

Note: The question is enhanced from this forum (http://salesforce.stackexchange.com/questions/65227/set-contains-decimal-to-check-if-the-elements-all-zero/65232#65232) ,but I am asking here in case anyone from Salesforce can answer this.

Thank you .

 
Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
Hello,

Set class definition: Represents a collection of unique elements with no duplicate values.

What is happening is that when you cast your list to a Set it's ignoring and excluding duplicated values in it. 0.0 == 0.00

Find out more here: https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_set.htm#apex_System_Set_methods (https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_set.htm#apex_System_Set_methods" target="_blank)

 Regards.

Don't forget to mark your thread as 'SOLVED' with the answer that best helps you.
Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
And regarding to the size being equals 2, well I confess that is puzzling.
unidhaunidha
@Zuinglio Lopes Ribeiro Junior, Ya it is really puzzling because it should remove duplicate values and print as one element right?
Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
As far as I know, yes it should!
unidhaunidha
The reply from Salesforce support:
Set represents a collection of unique elements with no duplicate values. In your scenario, you have passed duplicate values in a list and then assigned that list to set. Set only returns unique value from the list.
That is the reason why you are getting 0.0 as a result. size() returns the number of elements in the set (its cardinality). Since there are two values in the set, so it returns its size as 2. If there would be three values in the set, then the size will be returned as 3.