定义一个集合,用于存储3个学生对象 学生类的属性为:name,age,gender 定义一个工具类,用于获取集合中最大学生的年龄
时间: 2024-09-21 09:02:45 浏览: 63
首先,我们需要定义一个`Student`类,它有三个属性:`name`、`age`和`gender`。
```java
public class Student {
private String name;
private int age;
private String gender;
// 构造函数
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
// 获取和设置属性的方法
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; }
public String getGender() { return gender; }
public void setGender(String gender) { this.gender = gender; }
}
```
接下来,我们可以创建一个集合来存储三个`Student`对象,比如一个ArrayList:
```java
import java.util.ArrayList;
public List<Student> students = new ArrayList<>();
students.add(new Student("张三", 18, "男"));
students.add(new Student("李四", 20, "女"));
students.add(new Student("王五", 19, "男"));
```
现在我们定义一个工具类`StudentUtils`,里面包含一个静态方法`findOldestStudent()`,它遍历集合找出最年长的学生并返回其年龄:
```java
public class StudentUtils {
public static int findOldestStudent(List<Student> studentList) {
if (studentList.isEmpty()) {
throw new IllegalArgumentException("集合为空");
}
int oldestAge = studentList.get(0).getAge();
for (Student student : studentList) {
if (student.getAge() > oldestAge) {
oldestAge = student.getAge();
}
}
return oldestAge;
}
}
```
使用这个工具类时,只需传入我们的`students`集合即可:
```java
int oldestAge = StudentUtils.findOldestStudent(students);
System.out.println("最年长的学生年龄:" + oldestAge);
```
阅读全文