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;
}

}

public class Main { public static void main(String[] args) { ArrayList list = new ArrayList<>(); list.add(new Student('Tom', 18, 'male')); list.add(new Student('Jerry', 20, 'female')); list.add(new Student('Alice', 22, 'female'));

    int maxAge = 0;
    int maxIndex = 0;
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i).getAge() > maxAge) {
            maxAge = list.get(i).getAge();
            maxIndex = i;
        }
    }
    list.get(maxIndex).setName('小猪佩奇');

    for (Student student : list) {
        System.out.println('姓名:' + student.getName() + ',年龄:' + student.getAge() + ',性别:' + student.getGender());
    }
}

}

Java 学生类创建与操作:使用 ArrayList 查找年龄最大学生并修改姓名

原文地址: https://www.cveoy.top/t/topic/n952 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录