/*
定义一个学生类Student,包含三个属性姓名、年龄、性别,创建三个学生对象存入ArrayList集合中。
A:遍历集合遍历输出。
B:求出年龄最大的学生,然后将该对象的姓名变为:小猪佩奇。
*/
//测试类
import java.util.ArrayList;
public class Collection7 {
public static void main(String[] args) {
ArrayList<Student> a = new ArrayList<>();
a.add(new Student("王大大",18,"男"));
a.add(new Student("王二大",19,"男"));
a.add(new Student("王三小",15,"女"));
print(a);
System.out.println("---------");
change(a);
System.out.println("---------");
System.out.println(a);
}
public static void change(ArrayList<Student> a1){
int a=0;
int index=0;
for (int i1 = 0; i1 < a1.size(); i1++) {
if (a1.get(i1).getAge()>a){
index=i1;
a=a1.get(i1).getAge();
}
}
System.out.println("年龄最大的学生是"+a1.get(index).getName());
a1.get(index).setName("小猪佩奇");
}
public static void print(ArrayList<Student> a){
for (Student ss : a) {
System.out.println(ss);
}
}
}
//学生类
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", 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;
} |
|