java1.定义一个学生类,包含 姓名 年龄,成绩三个属性, 添加20个学生信息 按照年龄排序 按照成绩排序 按照年龄和成绩排序
时间: 2024-02-15 11:05:33 浏览: 138
好的,以下是Java中定义学生类的代码:
```java
public class Student implements Comparable<Student>{
private String name;
private int age;
private int grade;
public Student(String name, int age, int grade){
this.name = name;
this.age = age;
this.grade = grade;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public int getGrade(){
return grade;
}
@Override
public int compareTo(Student o) {
return this.age - o.age;
}
}
```
这个类中包含了姓名、年龄和成绩三个属性,并且实现了`Comparable`接口,以便后面可以按照年龄排序。
接下来,你可以创建20个学生的实例,代码如下:
```java
List<Student> students = new ArrayList<>();
students.add(new Student("Tom", 18, 90));
students.add(new Student("Jerry", 20, 85));
students.add(new Student("Lucy", 19, 92));
students.add(new Student("John", 21, 80));
students.add(new Student("Mary", 18, 95));
students.add(new Student("Bob", 20, 86));
students.add(new Student("Alice", 19, 88));
students.add(new Student("Lily", 21, 83));
students.add(new Student("Jack", 18, 89));
students.add(new Student("David", 20, 82));
students.add(new Student("Emma", 19, 91));
students.add(new Student("Sam", 21, 87));
students.add(new Student("Olivia", 18, 94));
students.add(new Student("Peter", 20, 84));
students.add(new Student("Grace", 19, 90));
students.add(new Student("Alex", 21, 81));
students.add(new Student("Sophia", 18, 88));
students.add(new Student("Kate", 20, 82));
students.add(new Student("Eric", 19, 93));
students.add(new Student("Lisa", 21, 85));
```
接下来,我们可以使用Java中的`Collections`类,按照年龄排序,代码如下:
```java
Collections.sort(students);
```
这个代码会返回按照年龄从小到大排序后的学生列表。
我们也可以按照成绩排序,代码如下:
```java
Collections.sort(students, new Comparator<Student>(){
@Override
public int compare(Student s1, Student s2){
return s2.getGrade() - s1.getGrade();
}
});
```
这个代码会返回按照成绩从大到小排序后的学生列表。
最后,我们可以按照年龄和成绩排序,代码如下:
```java
Collections.sort(students, new Comparator<Student>(){
@Override
public int compare(Student s1, Student s2){
if(s1.getAge() == s2.getAge()){
return s2.getGrade() - s1.getGrade();
}
else{
return s1.getAge() - s2.getAge();
}
}
});
```
这个代码会返回先按照年龄排序,再在年龄相同的情况下按照成绩从大到小排序后的学生列表。
阅读全文