Hello,

I have a question about ascending order sorting using the Comparabe interface:

When I add the keys of my Hash Map to a TreeSet object and implement the compareTo as below, I get descending order of sorting of names:

   public int compareTo (Accounts a)
                {
                    return a.name.compareTo(this.name);
                }


  // But when I change the above code to as below, it sorts the names in ascending order:

public int compareTo (Accounts a)
    {
        return this.name.compareTo(a.name);
    }

Could someone explain me why?

Thank you!

Using your first definition account1.compareTo(account2) will call account2.name.compareTo(account1.name) and using your second definition it will call account1.name.compareTo(account2.name). So using the result of the comparisson will be the other way around and thus the sort order is reversed.

Thank you for the reply!

Isn't TreeSet always sorting in ascending order?

If account2.name > account1.name, compareTo returns a positive number

If account1.name < account2.name, compareTo returns a negative number.

Either way, shouldn't the ascending order be the same since negative is always < positive and positive is always > negative

Thank you!

"ascending" is defined by the compareTo method.
a,b is ascending iff a.compareTo(b) >0

If you reverse the test inside the compareTo so that a.compareTo(b) <0 then you have just definied a,b as a descending sequence.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.