java语言定义一个Student类,包含姓名,年龄,初始化3个Student对象数组,按照年龄从小到大排序
时间: 2024-02-21 15:33:02 浏览: 17
以下是Java程序代码:
```
public class 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;
}
}
public class Main {
public static void main(String[] args) {
Student[] students = new Student[3];
students[0] = new Student("John", 21);
students[1] = new Student("Mary", 19);
students[2] = new Student("Bob", 23);
Arrays.sort(students, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.getAge() - s2.getAge();
}
});
for (Student student : students) {
System.out.println(student.getName() + " " + student.getAge());
}
}
}
```
输出结果为:
```
Mary 19
John 21
Bob 23
```