Java Array Sort descending?

Another solution is that if you’re making use of the Comparable interface you can switch the output values which you had specified in your compareTo(Object bCompared).

For Example :

public int compareTo(freq arg0) 
{
    int ret=0;
    if(this.magnitude>arg0.magnitude)
        ret= 1;
    else if (this.magnitude==arg0.magnitude)
        ret= 0;
    else if (this.magnitude<arg0.magnitude)
        ret= -1;
    return ret;
}

Where magnitude is an attribute with datatype double in my program. This was sorting my defined class freq in reverse order by it’s magnitude. So in order to correct that, you switch the values returned by the < and >. This gives you the following :

public int compareTo(freq arg0) 
{
    int ret=0;
    if(this.magnitude>arg0.magnitude)
        ret= -1;
    else if (this.magnitude==arg0.magnitude)
        ret= 0;
    else if (this.magnitude<arg0.magnitude)
        ret= 1;
    return ret;
}

To make use of this compareTo, we simply call Arrays.sort(mFreq) which will give you the sorted array freq [] mFreq.

The beauty (in my opinion) of this solution is that it can be used to sort user defined classes, and even more than that sort them by a specific attribute. If implementation of a Comparable interface sounds daunting to you, I’d encourage you not to think that way, it actually isn’t. This link on how to implement comparable made things much easier for me. Hoping persons can make use of this solution, and that your joy will even be comparable to mine.