java Set无序集合 HashSet 的对象元素唯一性

public class Demo{
    public static void main(String[] args) {


        Set<Person> set = new HashSet<>();

        set.add(new Person("张三",20));
        set.add(new Person("张三",20));
        set.add(new Person("李四",20));
        set.add(new Person("王五",20));

        System.out.println(set);


    }
}

public class Person {
private String name;
private int age;

public Person(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 String toString() {
    return "Person{" +
            "name='" + name + '\'' +
            ", age=" + age +
            '}';
}

@Override
public int hashCode() {
    return 110;
}

@Override
public boolean equals(Object obj) {

    boolean isEq = false;

   if (obj instanceof Person){
       Person p = (Person)obj;
       if (this.name != null && p.name != null && this.age == p.age && this.name.equals(p.name)){
           isEq = true;
       }
   }
   return isEq;
}
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页