[SalesForce] Sort list of class objects two ways

I want to sort a list of objects of a class by 2 ways.
I am able to do custom sort by overwriting the compareTo method.

But I have two lists and I want to sort them differently.

Can I still accomplish this by calling the list.sort() method?

global class myClass implements Comparable{

    public integer Total{get;set;}
    public integer numOfDays{get;set;}

    global Integer compareTo(Object compareTo) {
        myClass compareToEmp = (myClass)compareTo;
        if (Total == myClass.Total) return 0;
        if (Total > myClass.Total) return 1;
        return -1;        
    }
}

In the above example, how can I also be able to sort by "numOfDays"?

//UPDATE:

I actually wanted to sort list by single property.

But use different properties to sort different lists.

I ended up adding a new field to my class for sorting purpose.

global class myClass implements Comparable{

    public integer Total{get;set;}
    public integer numOfDays{get;set;}
    public boolean isA {get;set;}

    global Integer compareTo(Object compareTo) {
        myClass compareToEmp = (myClass)compareTo;
        if(isA){

        if (Total == myClass.Total) return 0;
        if (Total > myClass.Total) return 1;
            return -1; }
        else{
             if (Total == myClass.numOfDays) return 0;
        if (Total > myClass.numOfDays) return 1;
            return -1; 
        }       
    }
}

Best Answer

If you want to apply a secondary sort, it seems that should be in your == logical branch. It is hard to tell based on your naming what you are going for, because myClass is your object type, not your instance name (which is actually compareToEmp).

global Integer compareTo(Object obj)
{
    if (obj instanceOf MyClass)
    {
        MyClass compareTo = (MyClass)obj;
        if (compareTo.total > this.total) return -1;
        else if (compareTo.total < this.total) return 1;
        else // compareTo.total == this.total
        {
            if (compareTo.numOfDays > this.numOfDays) return -1;
            else if (compareTo.numOfDays < this.numOfDays) return 1;
        }
    }
    return 0;
}

If you want to be able to sort by one key or the other depending on your needs, you will want to implement some mechanism by which you can retrieve (and toggle) the value to sort by.

global class MyClass implements Comparable
{
    global static Boolean sortByTotal = true;

    global Integer total { get; private set; }
    global Integer dayCount { get; private set; }

    global Integer compareTo(Object obj)
    {
        if (obj instanceOf MyClass)
        {
            MyClass that = (MyClass)obj;
            return this.getSortValue() - that.getSortValue();
            // if you prefer, you can still compare the values and return 1 or -1
            // it may also be worth adding some null checks
        }
        return 0;
    }
    Integer getSortValue()
    {
        return (sortByTotal) ? total : dayCount;
    }
}