我正在实现一个简单的比较器,以在 Java 中按名称(按字母顺序)对 TreeSet 中的对象进行排序。结果与我的预期不同,我很难理解 java 的 String compareTo() 方法背后的逻辑。我的期望是字符串将按字母顺序排列。
这是代码清单:
学生班
enum Grade{ A, B, C; }
class Student {
private int studentId;
private String studentName;
private int rollNumber;
private double totalMarks;
private Grade grade;
public Student(int studentId, String studentName)
{
this.studentId=this.rollNumber=studentId;
this.studentName=studentName;
}
public Student(String studentName, int rollNumber)
{
this.studentId=this.rollNumber=rollNumber;
this.studentName=studentName;
}
public int getStudentId() {
return studentId;
}
public String getStudentName() {
return studentName;
}
/**
* @return the rollNumber
*/
public int getRollNumber() {
return rollNumber;
}
/**
* @param rollNumber the rollNumber to set
*/
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
/**
* @return the totalMarks
*/
public double getTotalMarks() {
return totalMarks;
}
/**
* @param totalMarks the totalMarks to set
*/
public void setTotalMarks(double totalMarks) {
this.totalMarks = totalMarks;
calculateGrade();
}
public void calculateGrade() {
if(this.totalMarks >= 60) this.grade = Grade.A;
else if(this.totalMarks > 40 && this.totalMarks < 60) this.grade = Grade.B;
else this.grade = Grade.C;
}
private Grade getGrade() {
return grade;
}
@Override
public String toString() {
return String.format("{name: %s, rollNumber: %d, totalMarks: %f, Grade: %s}",
studentName,
this.rollNumber,
this.totalMarks,
this.getGrade());
}
长风秋雁
ITMISS
相关分类