* 题目要求:自定义一个学生类Student,属性为姓名name,年龄age,创建一个ArrayList集合,存储自定义的学生类对象。
1、创建5个学生类对象,姓名随意,年龄使用自动生成的20-30的随机整数 (5分)
2、将创建的5个学生类对象存入ArrayList集合中 (5分)
- public static void main(String[] args) {
- ArrayList<Student> al = new ArrayList<>();
- Random rd = new Random();
- int num=1;
- while(num<=5){
- int age = rd.nextInt(11) + 20;
- al.add(new Student("stu", 1));
- num++;
- }
- System.out.println(al);
-
- getSingle(al);
- System.out.println(al);
- }
- public static void getSingle(ArrayList<Student> al) {
- ArrayList<Student> newList = new ArrayList<>();
- for (Student student : al) {
- if(!newList.contains(student)){
- newList.add(student);
- }
- }
- al.clear();
- al.addAll(newList);
- }
- }
- class Student {
- private String name;
- private int age;
- public Student() {
- super();
-
- }
- public Student(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- 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;
- }
- @Override
- public String toString() {
- return "Student [name=" + name + ", 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());
- 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;
- return true;
- }
-
- }
复制代码
3、将集合中的学生对象去重,去重的标准是:姓名和年龄都相同就认为是同一个学生 (5分)
|
|