0%

Student对象排序示范

要求:根据student对象的成绩排序
作者:黑曼巴小组
1:创建student对象,属性score,接口Comparable**_<Student_>,_重写_compareTo(Student stu)**

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class Student implements Comparable<Student>{
private String name;
private int ID;
private int score;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getID() {
return ID;
}

public void setID(int ID) {
this.ID = ID;
}

public int getScore() {
return score;
}

public void setScore(int score) {
this.score = score;
}

public Student() {
}

public Student(String name, int ID, int score) {
this.name = name;
this.ID = ID;
this.score = score;
}

@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Student{");
sb.append("name='").append(name).append('\'');
sb.append(", ID=").append(ID);
sb.append(", score=").append(score);
sb.append('}');
return sb.toString();
}

@Override
//实现Comparable的compareTo方法
public int compareTo(Student stu) {
// TODO Auto-generated method stub
return this.getScore()-stu.getScore();
}
}

2:创建测试类,调用Collections.sort方法排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class studentTest {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();//创建集合
students.add(new Student("李四",1,88));//添加元素
students.add(new Student("刘四",2,78));
students.add(new Student("张三",3,98));
students.add(new Student("王维",4,96));
//2:排序
Collections.sort(students);
//3:输出打印
for(Student s:students){
System.out.println(s);
}
}
}

按葫芦画瓢即可。