Making your own class 'Comparable'

Your Country class should implement Comparable:

public class Country implements Comparable<Country>

Then your compareTo method should look like this:

@Override
public int compareTo(Country anotherCountry) {
    return this.name.compareTo(anotherCountry.getName());
}

Note the signature of compareTo. The parameter can (and must) be of type Country, not Object. This is required because of the generic type parameter on Comparable. The upside is you don't have to check the type anymore. The downside is you can only compare Country to other Country objects (or its subtypes), but in most cases this is what you want anyway. If not you have to change the type parameter, e.g. if you use Comparable<Object> the signature of compareTo can be Object again. You can read more about generics here.


a Comparable should return:

a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

However, your code is returning only -1 or 0, which is not correct; this implies that this can be less than the other object, or equal, but not greater!

There is no need to modify the values returned by name.compareTo() - you can just return them directly.