How do I make 2 comparable methods in only one class?

What you need to do is implement a custom Comparator. And then use:

Collections.sort(yourList, new CustomComparator<YourClass>());

Specifically, you could write: (This will create an Anonymous class that implements Comparator.)

Collections.sort(yourList, new Comparator<YourClass>(){
    public int compare(YourClass one, YourClass two) {
        // compare using whichever properties of ListType you need
    }
});

You could build these into your class if you like:

class YourClass {

    static Comparator<YourClass> getAttribute1Comparator() {
        return new Comparator<YourClass>() {
            // compare using attribute 1
        };
    }

    static Comparator<YourClass> getAttribute2Comparator() {
        return new Comparator<YourClass>() {
            // compare using attribute 2
        };
    }
}

It could be used like so:

Collections.sort(yourList, YourClass.getAttribute2Comparator());

Leave a Comment