求java中类似学生信息管理系统中按学号,按姓名排序的代码

2025-02-13 07:15:07
推荐回答(2个)
回答1:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Sort {
public static void main(String[] args) {
Student p1 = new Student(1001, "小明", 20);
Student p2 = new Student(1002, "小红", 21);
Student p3 = new Student(1003, "小黑", 19);
List list = new ArrayList();
list.add(p1);
list.add(p2);
list.add(p3);
Collections.sort(list, new Comparator() {
/*
 * int compare(Student o1, Student o2) 返回一个基本类型的整型, 返回负数表示:o1 小于o2,
 * 返回0 表示:o1和o2相等, 返回正数表示:o1大于o2。
 */
public int compare(Student o1, Student o2) {
// 按照学生的学号进行升序排列
if (o1.getId() > o2.getId()) {
return 1;
}
if (o1.getId() == o2.getId()) {
return 0;
}
return -1;
}
});
write(list);
System.out.println("---------------------");
Collections.sort(list, new Comparator() {
/*
 * int compare(Student o1, Student o2) 返回一个基本类型的整型, 返回负数表示:o1 小于o2,
 * 返回0 表示:o1和o2相等, 返回正数表示:o1大于o2。
 */
public int compare(Student o1, Student o2) {
// 按照学生的年龄进行升序排列
if (o1.getAge() > o2.getAge()) {
return 1;
}
if (o1.getAge() == o2.getAge()) {
return 0;
}
return -1;
}
});
write(list);
}

public static void write(List list) {
for (Student s : list) {
System.out.println(s.getId() + "\t" + s.getName() + "\t"
+ s.getAge());
}

}

}


public class Student {
private int id ;
private String name;
private int age;
//构造方法
public Student(int id,String name,int age){
this.id = id;
this.name = name;
this.age = age;
}

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}

回答2:

那是你做了对不起他的事情了