[Solved] Implementing the Comparator interface [duplicate]


Here’s a Comparator inner class from my little project DBvolution:

private static class ClassNameComparator implements Comparator<Class<?>>, Serializable {

    private static final long serialVersionUID = 1L;

    ClassNameComparator() {
    }

    @Override
    public int compare(Class<?> first, Class<?> second) {
        String firstCanonicalName = first.getCanonicalName();
        String secondCanonicalName = second.getCanonicalName();
        if (firstCanonicalName != null && secondCanonicalName != null) {
            return firstCanonicalName.compareTo(secondCanonicalName);
        } else {
            return first.getSimpleName().compareTo(second.getSimpleName());
        }
    }
}

That might look complicated but it’s actually simple. The basic principle is below:

class ClassNameComparator implements Comparator<YourClass> {

ClassNameComparator() {
}

@Override
public int compare(YourClass first, YourClass second) {
    if (first > second){
        return 1;
    } else if (first == second){
        return 0;
    } else return -1;
}
}

You’ll need to replace YourClass with your class and change the tests to something more appropriate for your objects. Finally remember to check for nulls.

solved Implementing the Comparator interface [duplicate]