[Java] 纯文本查看 复制代码
//定义一个Student类,包含名称,年龄,性别(姓名,年龄,性别完全相同视为同一学生)
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;
}
//get/set
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;*/
if(age!=other.age && name!=other.name)
return false;
return true;
}
}
public class HashSetTest08 {
public static void main(String[] args) {
// 创建班级集合1
HashSet<Student> Class1 = new HashSet<>();
// 添加两个学生
Class1.add(new Student("zhangsan", 18));
Class1.add(new Student("lisi", 20));
Class1.add(new Student("wangwu", 17));
// 创建班级集合2
HashSet<Student> Class2 = new HashSet<>();
Class2.add(new Student("xiaojuan", 22));
Class2.add(new Student("xiaowang", 22));
Class2.add(new Student("lixizhen", 24));
// 创建学科集合
HashSet<HashSet> project = new HashSet<>();
// 添加班级
project.add(Class1);
project.add(Class2);
// 使用两种方法遍历学科集合,并打印出所有学生
for (HashSet<Student> s : project) {
for (Student stu : s) {
System.out.println(stu.getName() + " " + stu.getAge());
}
}
System.out.println("===================");
// 迭代器
Iterator<HashSet> it = project.iterator();
while (it.hasNext()) {
HashSet<Student> stu = it.next();
Iterator<Student> it2 = stu.iterator();
while (it2.hasNext()) {
Student st = it2.next();
System.out.println(st.getName() + " " + st.getAge());
}
}
}
}