# salesforce 零基础学习（六十三）Comparable实现Object列表数据的自定义排序

需求：实现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 }```

0 条评论

## 相关文章

660

4136

3499

3109

### 《笨办法学Python》 第37课手记

《笨办法学Python》 第37课手记 本节课是复习课。关键字是指系统预先定义好的含有特定含义的字符串或者函数，注意你在自定义函数时不能与关键字重名。可是该课中...

17610

602

723

3560

981

702