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

前端 未结 3 1695
借酒劲吻你
借酒劲吻你 2020-11-29 01:21

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 ca

3条回答
  •  离开以前
    2020-11-29 02:16

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

    Collections.sort(yourList, new CustomComparator());
    

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

    Collections.sort(yourList, new Comparator(){
        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 getAttribute1Comparator() {
            return new Comparator() {
                // compare using attribute 1
            };
        }
    
        static Comparator getAttribute2Comparator() {
            return new Comparator() {
                // compare using attribute 2
            };
        }
    }
    

    It could be used like so:

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

提交回复
热议问题