Comparable: Sorting Objects in Salesforce - Biswajeet Samal
文章推薦指數: 80 %
The Comparable interface adds sorting support for Lists that contain non-primitive types, that is, Lists of user-defined types.
TheComparableinterfaceaddssortingsupportforListsthatcontainnon-primitivetypes,thatis,Listsofuser-definedtypes.
ToaddListsortingsupportforyourApexclass,youmustimplementtheComparableinterfacewithitscompareTomethodinyourclass.
WhenaclassimplementstheComparableinterfaceithastoimplementamethodcalledcompareTo().ThismethodreturnsanIntegervaluethatistheresultofthecomparison.Inthatmethodthecodehastobewrittentodecideiftwoobjectsmatchorifoneislargerthantheother.
Theimplementationofthismethodshouldreturnthefollowingvalues:
0ifthisinstanceandobjectToCompareToareequal
>0ifthisinstanceisgreaterthanobjectToCompareTo
<0ifthisinstanceislessthanobjectToCompareTo
Let’stakealookatasimpleclassthattakesinanEmployeeobject,storestheemployee’sdatainitandallowsustosortalistofEmployeesbytheirEmployeeId.
ApexClass:
publicclassEmployeeimplementsComparable{
publicIntegerId;
publicStringName;
publicDecimalSalary;
publicEmployee(Integeri,Stringn,Decimals){
Id=i;
Name=n;
Salary=s;
}
publicIntegercompareTo(ObjectobjToCompare){
Employeeemp=(Employee)objToCompare;
if(Id==emp.Id){
return0;
}
elseif(Id>emp.Id){
return1;
}
else{
return-1;
}
}
}
ExecutethebelowcodeinDeveloperConsole.
List
延伸文章資訊
- 1Comparable Interface in Salesforce
To add List sorting support for your Apex class, you must implement the Comparable interface with...
- 2Comparable: Sorting Objects in Salesforce - Deadlypenguin
Like most Object Oriented languages, Apex will allow you to make an order List of objects that yo...
- 3Comparable Interface in Salesforce | MST Solutions
Salesforce provides an Interface called Comparable to implement a custom sort order for SObjects ...
- 4How to use comparable in Apex - YouTube
How to use comparable in ApexHow to sort object using comaparable in ApexHow to sort object in Ap...
- 5Comparable Interface : Way to perform sorting on wrapper ...
Apex provides comparable interface with compareTo method which can be used sort wrapper class. Yo...