学生类(需要重写hashCode()和equals())
package package7;
import java.util.Objects;
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
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 boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
测试类
package package7;
import java.util.HashSet;
public class HashDemo2 {
public static void main(String[] args) {
//创建集合对象
HashSet<Student> hs = new HashSet<>();
//创建学生对象
Student s1 =new Student("张三",21);
Student s2 =new Student("李四",22);
Student s3 =new Student("王五",23);
Student s4 =new Student("王五",23);
//把学生对象添加到集合中
hs.add(s1);
hs.add(s2);
hs.add(s3);
hs.add(s4);
//遍历集合(增强for循环)
for(Student s:hs){
System.out.println(s.getName()+", "+s.getAge());
}
}
}
标签:存储,return,name,对象,hs,age,学生,Student,public
From: https://www.cnblogs.com/knlf/p/16794944.html