java用借口排序学生学号姓名
时间: 2023-08-04 19:13:36 浏览: 49
首先,我们需要定义一个学生类,包含学号、姓名等属性。然后,定义一个接口,包含一个排序方法。最后,实现该接口并重写排序方法,用于按照学号或姓名对学生进行排序。
示例代码如下:
```java
public class Student {
private int id; // 学号
private String name; // 姓名
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
public interface SortInterface {
void sort(Student[] students);
}
public class IdSort implements SortInterface {
@Override
public void sort(Student[] students) {
Arrays.sort(students, Comparator.comparing(Student::getId));
}
}
public class NameSort implements SortInterface {
@Override
public void sort(Student[] students) {
Arrays.sort(students, Comparator.comparing(Student::getName));
}
}
```
使用示例:
```java
public static void main(String[] args) {
Student[] students = new Student[]{
new Student(1, "Tom"),
new Student(3, "Alice"),
new Student(2, "Bob")
};
SortInterface sortInterface = new IdSort();
sortInterface.sort(students);
for (Student student : students) {
System.out.println(student.getId() + " " + student.getName());
}
}
```
输出结果:
```
1 Tom
2 Bob
3 Alice
```