定义一个集合,用于存储3个学生对象。
学生类的属性为:name、age、gender
定义一个工具类,用于获取集合中最大学生的年龄。
javabean
package a03staticDemo3;
import java.util.ArrayList;
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;
}
}
util
package a03staticDemo3;
import java.util.ArrayList;
public class StudentUtil {
private StudentUtil() {}
public static int getMaxAge(ArrayList<Student> list) {
int max = list.get(0).getAge();
for (int i = 0; i < list.size(); i++) {
if (max < list.get(i).getAge()) {
max = list.get(i).getAge();
}
}
return max;
}
}
test
package a03staticDemo3;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<>();
Student stu1 = new Student("zhangsan", 18, "女");
Student stu2 = new Student("lisi", 19, "女");
Student stu3 = new Student("zhang", 20, "女");
list.add(stu1);
list.add(stu2);
list.add(stu3);
int maxAge = StudentUtil.getMaxAge(list);
System.out.println(maxAge);
}
}
运行结果
20