需求:
-
定义一个学生类Student,包含三个属性姓名、年龄、性别,私有成员变量,生成无参,有参构造方法,生成get/set方法。
-
创建三个学生对象存入ArrayList集合中。
-
找出年龄最大的学生,然后将该对象的姓名变为:小猪佩奇。
-
遍历集合输出对象属性信息。(输出格式如:姓名:张三, 年龄:23, 性别:男)
package test03;
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
ArrayList<Student> arrayList = new ArrayList<>();
//创建对象
Student stu = new Student("张三",23,"男");
Student stu1 = new Student("李四",20,"男");
Student stu2 = new Student("小红",19,"女");
//对象存入集合
arrayList.add(stu);
arrayList.add(stu1);
arrayList.add(stu2);
forSet(arrayList);
//遍历输出
for (Student student : arrayList) {
System.out.println(student.toString());
}
}
//定义方法判断年龄最大的,并更改姓名为:小猪佩奇
public static void forSet(ArrayList<Student> arrayList){
//
int a =0,j=0;
for (int i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i).getAge()>=a){
a = arrayList.get(i).getAge();
j = i;
//利用j获取最大值的下标
}
}
arrayList.get(j).setName("小猪佩奇");
}
}