1、定义一个学生类Student,包含三个属性姓名、年龄、性别,创建三个学生对象存入ArrayList集合中。
A:遍历集合遍历输出。
B:求出年龄最大的学生,让后将该对象的姓名变为:张棒棒。
代码如下
学生类
package com.softeem.lesson10.example;
public class Student {
private String name;
private String sex;
private int age;
public Student() {
// TODO Auto-generated constructor stub
}
public Student(String name, String sex, int age) {
super();
this.name = name;
this.sex = sex;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sex == null) ? 0 : sex.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (sex == null) {
if (other.sex != null)
return false;
} else if (!sex.equals(other.sex))
return false;
return true;
}
@Override
public String toString() {
return "Student [name=" + name + ", sex=" + sex + ", age=" + age + "]";
}
}
测试类
package com.softeem.lesson10.example;
import java.util.ArrayList;
import java.util.Arrays;
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student("李白", "男", 18);
Student s2 = new Student("小乔", "女", 28);
Student s3 = new Student("金克斯", "女", 20);
ArrayList<Student> list = new ArrayList<>(); //jdk1.7新特性
list.add(s1);
list.add(s2);
list.add(s3);
list.add(new Student("孙尚香","女",16));
list.add(new Student("大乔", "女", 88));
//声明临时数组存储所有学生的年龄
int[] arr = new int[list.size()];
for(int i = 0;i<list.size();i++) {
//取出每个学生的年龄装入数组
arr[i] = list.get(i).getAge();
System.out.println(list.get(i));
}
//对数组排序
Arrays.sort(arr);
//获取最后一个元素
int maxAge = arr[arr.length-1];
Student temp = null;
for(Student s:list) {
if(s.getAge() == maxAge) {
s.setName("张棒棒");
temp = s;
System.out.println("最大年龄的学生是:"+s);
}
}
list.remove(temp);
for (Student s : list) {
System.out.println(s);
}
}
}