Java-实现compareToArrayList自定义对象

问题描述

我正在类“历史记录”中实现并使用Comparable接口。这样,我想对History对象的ArrayList进行排序。

类构造函数如下:

public History(long id,String res,double deposit,double odds,String sport,double ret,String user_name,Date date) {
        
       this.id = id;
        this.res = res;
        this.deposit = deposit;
        this.odds = odds;
        this.sport = sport;
        this.ret = ret;
        this.user_name = user_name;
        this.date = date;
        
    }

@Override
    public int compareto(History o) {
        
        return this.getDepInt().compareto(o.getDepInt());
        
    }

此外,我有各自的方法来返回变量,例如“ getDepInt()”,getoddsInt()等。

这很好用,并且无法通过deposit变量对列表进行排序:

[172 Loss | 1000.0 | 1.1 | 1100.0 | F,170 Loss | 900.0 | 2.75 | 2475.0 | F,168 Won | 300.0 | 2.75 | 825.0 | F,169 Won | 200.0 | 2.75 | 550.0 | F,105 Loss | 175.0 | 2.75 | 481.25 | F,167 Won | 100.0 | 2.5 | 250.0 | F,166 Loss | 100.0 | 2.5 | 250.0 | F,165 Won | 100.0 | 2.5 | 250.0 | F,164 Won | 100.0 | 2.5 | 250.0 | F,171 Loss | 20.0 | 1.5 | 30.0 | F
]

但是,我希望能够对所有变量进行列表排序,因此用户可以选择他们希望对列表进行排序的方式,例如按“赢/亏”对列表进行排序。

我的问题是compareto(History o)方法会覆盖,而我实际上没有在我的代码调用方法。有解决这个问题的方法吗?

解决方法

这正是Comparator-Interface的用途。因为compareTo()接口的Comparable方法只能表示这种类型对象的“自然”顺序(按最常见的功能顺序)。

要通过任意功能实现比较,请编写一些实现Comparator的类,例如...

public class HistoryOddsComparator implements Comparator<History> {
    @Override
    public int compare(History o1,History o2) {
        return o1.getOddsInt() - o2.getOddsInt();
    }
}

...以便您可以致电...

Collections.sort(historyList,new HistoryOddsComparator());

(只是一个例子!)

,

您应该使用比较器。 示例为here。 只需为要排序的每个字段实现一个比较器。