Java中使用泛型可以实现比较任何类型的数据。具体实现可以通过实现Comparable接口或者Comparator接口来实现,例如:
public class Student implements Comparable
//...
//实现compareTo方法
@Override
public int compareTo(Student o) {
if (this.score > o.score) {
return 1;
} else if (this.score < o.score) {
return -1;
} else {
return 0;
}
}
}
public class StudentComparator implements Comparator
@Override
public int compare(Student o1, Student o2) {
if (o1.getAge() > o2.getAge()) {
return 1;
} else if (o1.getAge() < o2.getAge()) {
return -1;
} else {
return 0;
}
}
}
在使用时,可以直接使用Collections.sort()方法进行排序:
List
以上示例中,可以比较String,int,double等任何类型的数据,并且可以针对不同的需求实现不同的比较方式。
下一篇:比较任意类型的两个变量的函数