本文共 2424 字,大约阅读时间需要 8 分钟。
该学生类通过私有字段实现对象数据封装,包含姓名和年龄两个属性。通过公有无参数、单参数构造方法支持对象的初始化。以下是该类的具体实现:
public 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 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; }}
基于上述学生类,本文设计了一个集合嵌套遍历的解决方案,适用于班级管理场景。具体实现如下:
import java.util.ArrayList;public class Test1 { public static void main(String[] args) { ArrayList bigArrayList = new ArrayList(); ArrayList firstArrayList = new ArrayList(); ArrayList secondArrayList = new ArrayList(); // 添加学生信息 Student s1 = new Student("唐僧", 21); Student s2 = new Student("沙僧", 22); Student s3 = new Student("猪八戒", 23); // 第一个班级信息 firstArrayList.add(s1); firstArrayList.add(s2); firstArrayList.add(s3); bigArrayList.add(firstArrayList); // 第二个班级信息 Student s4 = new Student("曹操", 18); Student s5 = new Student("刘备", 40); Student s6 = new Student("孙权", 28); secondArrayList.add(s4); secondArrayList.add(s5); secondArrayList.add(s6); bigArrayList.add(secondArrayList); // 遍历输出 for (ArrayList array : bigArrayList) { for (Student s : array) { System.out.println(s.getName() + "---" + s.getAge()); } } }}
以上实现通过多层嵌套集合结构,确保了班级间学生信息的独立管理和整体容斥处理。通过这种方式,不同班级的学生可以在同一顶级集合中统一管理,实现灵活的数据扩展和维护。
转载地址:http://vgcez.baihongyu.com/