在Java中使用Comparable实现VO的多个动态字段 [英] Using Comparable for multiple dynamic fields of VO in java

查看:1313
本文介绍了在Java中使用Comparable实现VO的多个动态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级

public class StudentVO {
   int age;
   String name;  
}

我在两个不同的领域使用了同一个班级。在一个地方,我需要根据年龄排序。在另一个地方,我需要根据名称排序,在
另一个地方,我可能需要根据年龄和名称进行排序。我怎样才能做到这一点?
如果我可以覆盖一个字段 compareTo()

I used the same class in two different areas. At one place i need to sort based on the age. In another place I need to sort based on the name and in another place i may need sorting based on both age and name. How can I do this? If one field I can override compareTo().

是否可以这样做?

推荐答案

1)你应该写两个Comparator 分别对年龄和名称进行排序,然后使用 Collections.sort(列表,比较器)。这样的事情:

1)You should write two Comparator for sorting on age and name separately, and then use the Collections.sort(List,Comparator). Something like this:

class StudentVO {
  private String name;
  private int age;
  public String getName() {
      return name;
  }
  public void setName(String name) {
      this.name = name;
  }
  public int getAge() {
      return age;
  }
  public void setAge(int age) {
      this.age = age;
  }
}

class AgeComparator implements Comparator<StudentVO> {

@Override
public int compare(StudentVO o1, StudentVO o2) {
    Integer age1 = o1.getAge();
    Integer age2 = o2.getAge();
    return age1.compareTo(age2);
  }

}

class NameComparator implements Comparator<StudentVO> {

  @Override
  public int compare(StudentVO o1, StudentVO o2) {
      return o1.getName().compareTo(o2.getName());
  }

}

然后使用它们,进行排序基于年龄

And then use them, To sort based on age:

Collections.sort(list,new AgeComparator());

基于名称进行排序

Collections.sort(list,new NameComparator());

2)如果您认为列表 StudentVO 有一些自然的排序顺序,假设按年龄排序。然后,使用 Comparable 获取年龄比较器代表名称

2) If you think that the List of StudentVO has some natural order of sorting, say suppose sort by age. Then, use Comparable for age and Comparator for name.

 class StudentVO implements Comparable<StudentVO>{
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public int compareTo(StudentVO o) {
        return ((Integer)getAge()).compareTo(o.getAge());
    }
}

class NameComparator implements Comparator<StudentVO> {

    @Override
    public int compare(StudentVO o1, StudentVO o2) {
        return o1.getName().compareTo(o2.getName());
    }

 }

然后使用它们,进行排序基于年龄

And then use them, To sort based on age:

Collections.sort(list);

基于名称进行排序

Collections.sort(list,new NameComparator());

这篇关于在Java中使用Comparable实现VO的多个动态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆