求解答疑惑
一下是自己编写的一道java练习题的代码
所得实际结果与预输出结果有差异
预输出结果为: ArrayList集合中的学生对象按成绩排序,降序排序输出,如果成绩一样就按年龄升序排序
[Student{name='liuSan', age=20, score=90.0}, Student{name='liSi', age=22, score=90.0}, Student{name='wanGwu', age=20, score=99.0}, Student{name='sunLiu', age=22, score=100.0}]
Student{name='sunLiu', age=22, score=100.0}
Student{name='wanGwu',age=20,score=99.0}
Student{name='liuSan', age=20, score=90.0}
Student{name='liSi', age=22, score=90.0}
实际输出结果wei:
[Student{name='liuSan', age=20, score=90.0}, Student{name='liSi', age=22, score=90.0}, Student{name='wanGwu', age=20, score=99.0}, Student{name='sunLiu', age=22, score=100.0}]
Student{name='sunLiu', age=22, score=100.0}
Student{name='liuSan', age=20, score=90.0}
Student{name='liSi', age=22, score=90.0}
以下为具体代码:
```java
import java.util.*;
public class Homework03 {
public static void main(String[] args) {
Student s1 = new Student("liuSan",20,90.0F);
Student s2 = new Student("liSi",22,90.0F);
Student s3 = new Student("wanGwu",20,99.0F);
Student s4 = new Student("sunLiu",22,100.0F);
ArrayList c = new ArrayList<>();
c.add(s1);
c.add(s2);
c.add(s3);
c.add(s4);
System.out.println(c);
TreeSet c1 = new TreeSet<>(new AComparator());
c1.addAll(c);
for (Student stu : c1) {
System.out.println(stu);
}
}
}
class AComparator implements Comparator{
@Override
public int compare(Student o1, Student o2) {
if(o1.score - o2.score > 0 || o1.score - o2.score < 0) {
return o2.age - o1.age;
}
return o1.age - o2.age;
}
}
class Student implements Comparable{
String name ;
int age ;
float score ;
public Student() {
}
public Student(String name, int age, float score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
@Override
public int compareTo(Student s) {
if(this.score > s.getScore()) return 1;
else if(this.score < s.getScore()) return -1;
else if(this.score == s.getScore()) {
if (this.age > s.getAge()) return -1;
else if (this.age == s.getAge()) return 0;
return 1;
}
return 1;
}
@Override
public String toString() {
return "Student{" +
"name='" +name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
```
试试这个:
class AComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
if (o1.score == o2.score) {
return o1.age - o2.age;
} else {
return Float.compare(o2.score, o1.score);
}
}
}
这里我们先比较成绩,如果成绩相等,再比较年龄,实现了您的预期结果。注意在比较成绩时使用 Float.compare() 方法比较浮点数,而不是使用减法来比较。这是因为在 Java 中使用减法比较浮点数时可能会存在精度误差,从而导致比较结果不正确。