Using Comparable for multiple dynamic fields of VO in java

后端 未结 7 1836
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 11:36

I have a class

public class StudentVO {
   int age;
   String name;  
}

I used the same class in two different areas. At one place i need t

7条回答
  •  一生所求
    2020-11-28 12:11

    I recently had to solve this problem, too. Not sure if this is exactly the same scenario as yours, but I had to write an in-memory sort for zero or more columns of a grid, handwaving over OOM conditions, etc, because my problem was very limited in scope.

    I wrote a comparator for each column and a comparator that took a list of comparators. As I identified which columns needed to be sorted and in what order, I added an instance of the corresponding comparator to the list of comparators. Then, use the chained comparator to execute the actual sort.

    public class MyObject
    {
        private String name;
        private int age;
        private Date registered;
    }
    

    So, something like this for each comparator:

    public class NameComparator
        implements Comparator
    {
        public int compare(MyObject o1, MyObject o2)
        {
            return o1.getName().compareTo(o2.getName);
        }
    }
    

    This for the chained comparator:

    public class ChainedComparator
        implements Comparator
    {
        public int compare(MyObject o1, MyObject o2) {
            for(Comparator comparator : comparators) {
                int result = comparator.compare(o1,o2);
                if(result != 0) {
                    return result;
                }
            }
            return 0;
        }
    }
        private List> comparators = new ArrayList<>();
    }
    

    Left to your imagination is parsing the sorts and building the chained comparator. I actually made this a bit more complicated because I also incorporated a direction which I implemented by swapping the order of parameters in the call to the sub-comparator in the chained comparator as needed.

提交回复
热议问题