Using Comparable for multiple dynamic fields of VO in java

后端 未结 7 1696
伪装坚强ぢ
伪装坚强ぢ 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:21

    In java, you have two main way to compare objects. The first is for the class itself to implement the Comparable interface which will mean only one implementations. The second is to have classes implements Comparator interface. This way, you can have multiple comparators for the same class.

    This mean that you could define for exemple 3 diffenrent Comparators on your StudentVo class : one that compare only on the name, another that compare the ages and the last one that both properties.

    In your application, you use the implementation that suit you need based on what you want to compare. In one place, you will compare students on age Collections.sort(myStudents , new CompareStudentOnAge()). In another place, you use another implementation.

    You can find some explanations in this blog post : http://javarevisited.blogspot.fr/2011/06/comparator-and-comparable-in-java.html

    0 讨论(0)
提交回复
热议问题