此题目为测试类,JavaBean和工具类的训练
定义学生工具类
- 需求:定义一个集合,用于存储3个学生对象
- 学生类的属性为:name,age,gender
- 定义一个工具类,用于获取集合中最大学生的年龄。
1. 测试类
package staticdemo;
import java.util.ArrayList;
public class TestDemo {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<>();
Student stu1 = new Student("张三",18,"男");
Student stu2 = new Student("李四",20,"男");
Student stu3 = new Student("王五",23,"男");
list.add(stu1);
list.add(stu2);
list.add(stu3);
int maxAgeStudent = StudentUtil.getMaxAgeStudent(list);
System.out.println(maxAgeStudent);
}
}
2. JavaBean类(学生类)
package staticdemo;
public class Student {
private String name; //姓名
private int age; //年龄
private String gender; //性别
public Student() {
}
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;
}
}
3. 工具类
package staticdemo;
import java.util.ArrayList;
public class StudentUtil {
private StudentUtil(){}
//获取集合中最大学生的年龄
//静态方法
public static int getMaxAgeStudent(ArrayList<Student> list){
//定义一个最大值参照物
int max = list.get(0).getAge();
for (int i = 0; i < list.size(); i++) {
//为了防止每次使用三目运算符和赋值都反复嗲用get()和getAge()方法。可以使用变量接收
int tempAge = list.get(i).getAge();
max = max > tempAge ? max : tempAge;
}
return max;
}
}