salesforce 零基礎學習(六十三)Comparable實現Object列表資料的自訂排序

來源:互聯網
上載者:User

標籤:ima   static   顯示   介面   邏輯   log   pre   result   alt   

項目中通常有些需求為需要將某個sObject的資料列表按照某種規則排序顯示到前台頁面上,但是list上面的sort遠遠滿足不了複雜的功能,此種情況需要自訂比較兩個object大小的方法,所以需要建立Compare相關的類實現Comparable介面。

 需求:實現Goods__c列表排序,GoodsBrand__c為華為的按照價格升序排序,GoodsBrand__c為聯想的按照價格降序排列。

 1 public without sharing class ComparedGoods implements Comparable{ 2     private Goods__c goods{get;set;} 3      4     private static final String GOODS_BRAND_HUAWEI = ‘華為‘; 5      6     private static final String GOODS_BRAND_LIANXIANG = ‘聯想‘; 7      8     public ComparedGoods(Goods__c obj) { 9         goods = obj;10     }11     12     public Integer compareTo(Object objectToCompareTo) {13             Goods__c comparedGoods = (Goods__c)objectToCompareTo;14             Integer comparedResult = 0;15             if(comparedGoods.GoodsBrand__c == GOODS_BRAND_HUAWEI) {16                 if(goods.GoodsPrice__c > comparedGoods.GoodsPrice__c) {17                     comparedResult = 1;18                 } else if(goods.GoodsPrice__c < comparedGoods.GoodsPrice__c) {19                     comparedResult = -1;20                 }21             } else if(comparedGoods.GoodsBrand__c == GOODS_BRAND_LIANXIANG) {22                 if(goods.GoodsPrice__c > comparedGoods.GoodsPrice__c) {23                     comparedResult = -1;24                 } else if(goods.GoodsPrice__c == comparedGoods.GoodsPrice__c) {25                     comparedResult = 0;26                 } 27                 else if(goods.GoodsPrice__c < comparedGoods.GoodsPrice__c) {28                     comparedResult = 1;29                 }30             }31             return comparedResult;32     }33 }

用法:

總結:針對object需要比較大小的時候,可以實現Comparable介面,在其compareTo方法中實現比較的邏輯即可。此篇有錯誤的地方歡迎指正,有問題歡迎留言。

salesforce 零基礎學習(六十三)Comparable實現Object列表資料的自訂排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.