HashSet是通过equals方法以及hashcode方法来判断对象是否重复。HashSet类对象是否重复判断。通过重写equals方法实现。
import java.util.HashSet;
import java.util.Iterator;
class Student {
public String name;
public int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
//方便打印
public void show(){
System.out.println(this.name+"---"+this.age);
}
//根据学生姓名及年龄判断对象是否重复
//名字一样年龄不是不会重复的
@Override
public boolean equals(Object obj) {
String tname = ((Student)obj).name; //强制转换类型获取学生的名字
int tage = ((Student)obj).age;
//只有名字和年龄都相同,才会认为是同一个对象
if(name.equals(tname) && (age == tage)){
return true;
}else{
return false;
}
}
}
public static void main(String[] args) {
//要求:年龄和名字都相同时才被认为是一个重复的对象
HashSet<Student> hs = new HashSet<>();
hs.add(new Student("花花", 45));
hs.add(new Student("红红", 22));
hs.add(new Student("金毛", 15));
hs.add(new Student("花花", 18)); //虽然名字相同,但是年龄不同,所以可以加进去的
hs.add(new Student("花花", 45)); //因为重复加不进来
//遍历集合,使用Itreator遍历
Iterator<Student> it = hs.iterator();
while(it.hasNext()){
it.next().show();
}
}