求解答疑惑
一下是自己编写的一道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<Student> c = new ArrayList<>();
c.add(s1);
c.add(s2);
c.add(s3);
c.add(s4);
System.out.println(c);
TreeSet<Student> c1 = new TreeSet<>(new AComparator());
c1.addAll(c);
for (Student stu : c1) {
System.out.println(stu);
}
}
}
class AComparator implements Comparator<Student>{
@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<Student>{
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 +
'}';
}
}
```