今天在写一个类型时,需要覆写compare方法,源代码如下:

1
2
3
4
5
6
public int compare(Object arg0, Object arg1){
	Student stu0 = (Student)arg0;
	Student stu1 = (Student)arg1;
	int flag = stu0.TotalScore.compareTo(stu1.TotalScore);
	return flag;
}

编译的时候,出现了”无法取消引用”的错误,经检查,发现原来是一个低级的错误,compareTo的方式是对象的方法,而我直接用的是基本数据类型(即代码中的TotalScore,定义为double类型),将其封装到对象中即可解决问题。

1
2
3
4
5
6
public int compare(Object arg0, Object arg1){
	Student stu0 = (Student)arg0;
	Student stu1 = (Student)arg1;
	int flag = (Double.valueOf(stu0.getTotalScore())).compareTo(Double.valueOf(stu1.getTotalScore()));
	return flag;
}