Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

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

I've got one class, that I sort it already by one attribute. Now I need to make another thing, that I need to create another way to sort my data. How can I make it, so I can choose between the two methods. The only command I know is Collections.sort that will pick up the method compareTo from the class I want to compare its data.

Is it even possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...