定义一个学生类Student,包含三个属性姓名、年龄、性别,创建三个学生对象存入ArrayList集合中。
A:遍历集合遍历输出。
B:求出年龄最大的学生,然后将该对象的姓名变为:小猪佩奇。
public class Student {
public String name;
public int age;
public String xingbie;
public Student(String name, int age, String xingbie) {
this.name = name;
this.age = age;
this.xingbie = xingbie;
}
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 getXingbie() {
return xingbie;
}
public void setXingbie(String xingbie) {
this.xingbie = xingbie;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", xingbie='" + xingbie + '\'' +
'}';
}
}
public class Di7 {
public static void main(String[] args) {
ArrayList<Student> arr = new ArrayList<>();
Student s1 = new Student("小陆",18,"男");
Student s2 = new Student("陆",19,"女");
Student s3 = new Student("大陆",20,"男");
arr.add(s1);
arr.add(s2);
arr.add(s3);
for (Student s : arr) {
System.out.println(s);
}
Student ss = listTest(arr);
System.out.println(ss);
// System.out.println(listTest(arr));
}
public static Student listTest(ArrayList<Student> arr) {
int in = 0;
int i = 0;
for (int j = 0; j < arr.size(); j++) {
if(arr.get(j).getAge()>in){
in=arr.get(j).getAge();
i=j;
}
}
arr.get(i).setName("小猪佩奇");
return arr.get(i);
}
} |
|