public class Student<NU,N,A,R,O> {
private final NU nu;
private final N n;
private final A a;
private final R r;
private final O o;
public Student(NU nu, N n, A a, R r, O o) {
this.nu = nu;
this.n = n;
this.a = a;
this.r = r;
this.o = o;
}
public N getN() {
return n;
}
public A getA() {
return a;
}
public R getR() {
return r;
}
@Override
public String toString() {
return "\n Student[" +
"Порядковый номер = " + nu +
", Имя = '" + n + '\'' +
", Возраст = " + a +
", Оценка = " + r +
", Олимпядник = " + o +
']' ;
}
}
COMPARATOR
public class StudentsComparatorsAgeAndRating implements Comparator<Student<Integer,String,Integer,Double,Boolean>> {
@Override
public int compare(Student o1, Student o2) {
if (!(o1.getA().equals(o2))) {
return (Integer)o1.getA() - (Integer)o2.getA();
}
return 0;
}
}
public class StudentsComparatorsName implements Comparator<Student<Integer, String, Integer, Double, Boolean>> {
@Override
public int compare(Student o1, Student o2) {
return (Integer)o1.getN().toString().length() - (Integer) o2.getN().toString().length();
}
}
public class StudentsComparatorsRating implements Comparator<Student<Integer, String, Integer, Double, Boolean>> {
@Override
public int compare(Student o1, Student o2) {
BigDecimal bd = BigDecimal.valueOf((Double)o1.getR());
BigDecimal bd1 = BigDecimal.valueOf((Double)o2.getR());
return bd1.compareTo(bd);
}
}
问题是,我可以在没有类型转换的情况下比较泛型吗?
为了避免比较器类中的类型转换,您应该在这些类中指定完整类型:
因为当使用
public int compare(Student o1, Student o2)
没有指定特定类的方法时,编译器不会“理解”哪个类将用于 fieldsStudent
。摆脱对比较器不必要的冗长描述的另一种方法是创建一个具有类型规范和构造函数的类,并为这样的类创建比较器: