feat(class38): 匿名内部类数组排序示例

- 新增 Student 类,包含姓名、年龄、身高和性别属性
- 新增 Test4 类,用于测试学生数组的排序功能
- 使用 Lombok 注解简化 Student 类的代码
- 在 Test4 类中创建学生数组并进行年龄排序
This commit is contained in:
2025-07-29 20:34:03 +08:00
parent 145ecbc6aa
commit 0812ce73f9
2 changed files with 52 additions and 0 deletions

16
src/class38/Student.java Normal file
View File

@@ -0,0 +1,16 @@
package class38;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private String name;
private int age;
private double height;
private char sex;
}

36
src/class38/Test4.java Normal file
View File

@@ -0,0 +1,36 @@
package class38;
import java.util.Arrays;
import java.util.Comparator;
public class Test4 {
public static void main(String[] args) {
Student[] students = new Student[6];
students[0] = new Student("般素素", 35, 171.5, '女');
students[1] = new Student("杨幂", 28, 168.5, '女');
students[2] = new Student("张无忌", 25, 181.5, '男');
students[3] = new Student("小昭", 19, 165.5, '女');
students[4] = new Student("赵敏", 27, 167.5, '女');
students[5] = new Student("刘亦菲", 36, 168, '女');
Arrays.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//比较返回正数表示o1比o2大返回负数表示o1比o2小返回0表示o1和o2相等
// if(o1.getAge()> o2.getAge()){
// return 1;
// } else if (o1.getAge()< o2.getAge()) {
// return -1;
// }else {
// return 0;
// }
return o1.getAge()-o2.getAge();
}
});
for (Student student : students) {
System.out.println(student);
}
}
}