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

百般思念 提交于 2019-11-26 09:25:52

问题


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?


回答1:


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



回答2:


You can only have one compareTo() method in your class.

If you want to sort the same class more than one way, create Comparator implementations.




回答3:


If the two methods require the exact same footprint, you may be inappropriately overloading a single class with multiple uses, which would be resolved by fixing your class hierarchy - like instead of using "shape", subclass it with "oval", "rectangle", etc.

If subclassing doesn't make sense, you need to create different comparison classes. In Java, you often use a Comparator for comparisons. Create several (or create a configurable comparator): IsbnComparator, AuthorComparator, etc.

Oh, and the configurable option would be:

 BookComparator implements Compartor {
   enum FIELD { AUTHOR, ISBN, ... };
   setSortOrder(int rank, FIELD field){...}
 }


来源:https://stackoverflow.com/questions/4432774/how-do-i-make-2-comparable-methods-in-only-one-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!