https://blog.csdn.net/weixin_57204093/article/details/129791857
package com.qf.b_hashSet;
import java.util.HashSet;
import java.util.Set;
class Person {
int id;
String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
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;
Person other = (Person) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
public class Demo2 {
public static void main(String[] args) {
Set<Person> set = new HashSet<Person>();
Person person1 = new Person(1, "黑龙");
Person person2 = new Person(2, "花花");
Person person3 = new Person(1, "黑龙");
set.add(person1);
set.add(person2);
set.add(person3);
System.out.println(set);
//现在存了三个对象。
//重写equlas和hashCode方法
}
}
总结: 如果将对象存入到hashSet中的时候,必须重写当前类的equals和hashCode方法 为了保证对象的内容不重复。