0

I'm implementing and using the Comparable interface in my class "History". This way I want to sort an ArrayList of History objects.

The class constructor looks like this:

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());
        
    }

Also, I have respective methods to return the variables e.g. "getDepInt()", getOddsInt() etc.

This works fine, and im able to sort the list by the deposit variable:

[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
]

However, I want to be able to sort the list on all varibles, so the user can select which way the they want to sort the list e.g. sort the list by "Won/Loss".

My problem is that the compareTo(History o) method overwrites, and im not actually calling the method in my code. Is there a way of solving this?

egx
  • 389
  • 2
  • 14
  • 2
    I think you need to use the Comparator Interface here and not the Comparable. Check this for more information https://www.geeksforgeeks.org/comparator-interface-java/ – pallavi richhariya Aug 12 '20 at 08:39

2 Answers2

3

This is exactly what the Comparator-Interface is for. Because the compareTo() method of the Comparable interface is only there to represent the "natural" order of objects of this type (order by the most common feature).

To implement comparison by arbitrary features write a handful of classes implementing Comparator, such as ...

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

... so you can call ...

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

(just an example!)

bkis
  • 2,530
  • 1
  • 17
  • 31
  • Thank you sir. I was not aware of this, so im glad that you linked me up. This solved my problem perfectly. – egx Aug 12 '20 at 09:45
1

You should use Comparator. The example is here. Just implement one comparator for every field you want to sort by.

Rolaman
  • 33
  • 7