二、定义一个学生类Student,包含三个属性姓名、年龄、性别,创建三个学生对象存入ArrayList集合中。
- A:使用迭代器遍历集合。
- B:求出年龄最大的学生,然后将该对象的姓名变为:小猪佩奇。
import java.util.ArrayList;
import java.util.Iterator;
public class Test {
public static void main(String[] args) {
Student[] stu = new Student[3];
stu[0] = new Student("张三",12,"男");
stu[1] = new Student("李四",16,"女");
stu[2] = new Student("王五",13,"男");
ArrayList<Student> list = new ArrayList<>();
for (int i = 0; i < stu.length; i++) {
list.add(stu[i]);
}
Iterator it = list.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
System.out.println("----------------------------");
int maxAge = 0;
for (int i = 0; i < list.size(); i++) {
int age = list.get(i).getAge();
if(age > maxAge){
maxAge = age;
}
}
int index = 0;
for (int i = 0; i < list.size(); i++) {
int age = list.get(i).getAge();
if(age == maxAge){
index = i;
}
}
list.get(index).setName("小猪佩奇");
for (Student student : list) {
System.out.println(student);
}
}
}