1.测试类
import java.util.HashSet;
public class Test {
@org.junit.Test
public void test1(){
Person person1 = new Person(1001,"AA");
Person person2 = new Person(1002, "BB");
HashSet hashSet = new HashSet();
hashSet.add(person1);
hashSet.add(person2);
System.out.println(hashSet);//[Person{id=1002, name='BB'}, Person{id=1001, name='AA'}]
person1.name = "CC";
System.out.println(hashSet);//[Person{id=1002, name='BB'}, Person{id=1001, name='CC'}]
hashSet.add(person1);//person1的hashCode前后就不一样了,可以添加
System.out.println(hashSet);//[Person{id=1002, name='BB'}, Person{id=1001, name='CC'}, Person{id=1001, name='CC'}]
hashSet.add(new Person(1001,"AA"));//这个hashCode值和原来的person1是一样的,但是equals不一样,可以添加
System.out.println(hashSet);//[Person{id=1002, name='BB'}, Person{id=1001, name='CC'}, Person{id=1001, name='CC'}, Person{id=1001, name='AA'}]
}
}
2.Person类
import java.util.Objects;
public class Person {
int id;
String name;
public Person() {
}
public Person(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return id == person.id &&
Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
总结:hashSet和LinkedHashSet是先计算哈希值确定存储位置,然后equals
TreeSet是通过比较器来确定存储顺序(自然排序和定制排序)