1

如果有一个StudentUnion类定义了相应的比较器,并且当它成为Student类的成员对象时,它希望以相同的因素在集合中排序(按学生会排序),那么如何避免重新编码另一个比较器几乎和StudentUnionComparator? 这种情况有没有最好的设计?

public class Student{
    ....
    private StudentUnion;
    ....
}

public class StudentUnionComparator implements Comparator<StudentUnion>{
    public int compare(StudentUnion s1, StudentUnion s2){
        ....
        return result // 1 or 0;
    }
}
4

3 回答 3

2

Comparator最简单的方法是为您的Student类创建一个,您将使用StudentUnion它持有的实例进行比较。

列出这个:

public class StudentComparator implements Comparator<Student> {
  public int compare(Student s1, Student s2) {
    return s1.getStudentUnion().compareTo(s2.getStudentUnion();
    }
  }

编辑:这使您可以灵活地编写另一种方式来对您进行Student排序StudentUnion。就像波西米亚人的名字一样。

于 2013-07-16T15:08:37.917 回答
2

制作StudentUnion工具Comparable

public class StudentUnion implements Comparable<StudentUnion> {

    public int compareTo(StudentUnion s) {
        ....
        return result // 1 or 0;
    }
}

然后也有Student实现Comparable,使用第StudentUnion一个,然后是其他一些属性,以防StudnetUnion比较相同:

public class Student implements Comparable<Student> {
    public int compareTo(Student s) {
        int result = studentUnion.compareTo(s.studentUnion);
        if (result != 0)
            return result;
        // use another field like name to break ties on StudentUnion
        return name.compareTo(name);
    }
}
于 2013-07-16T15:09:11.460 回答
0

您可以使用 StudentUnion 的 Object Instant。对象将接受所有类。

public class CommonComparator implements Comparator<Object> {
    public int compare(Object s1, Object s2){
        ....
        return result // 1 or 0;
    }
} 
于 2013-07-16T15:00:51.010 回答