java语言定义一个Student类,包含姓名,年龄,初始化3个Student对象数组,按照年龄从小到大排序
时间: 2024-02-21 22:39:09 浏览: 41
public class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Student other) {
return Integer.compare(this.age, other.age);
}
}
public class Main {
public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student("Alice", 20);
students[1] = new Student("Bob", 18);
students[2] = new Student("Charlie", 22);
Arrays.sort(students);
for (Student student : students) {
System.out.printf("%s %d\n", student.getName(), student.getAge());
}
}
}
阅读全文