HashSet 存储自定义元素需要注意的要点

1.HashSet 存储自定义元素时必须要重写hashCode和equals方法,这样才能保证重复的元素只存储一次。

package cn.itcast.Day10;

import java.util.Objects;

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

   public Person() {
   }

   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 boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;
      Person person = (Person) o;
      return age == person.age &&
              Objects.equals(name, person.name);
   }

   @Override
   public int hashCode() {
      return Objects.hash(name, age);
   }

   @Override
   public int compareTo(Person o) {
      return o.age-this.age;
   }
}

 

2.存储自定义类型元素

package cn.itcast.Day10;

import java.util.HashSet;

public class HashSet_three {
    public static void main(String[] args) {
        Person p1=new Person("张三",18);
        Person p2=new Person("张三",18);
        Person p3=new Person("张三",19);
        //HashSet存储自定义类型
        HashSet se=new HashSet<>();
        se.add(p1);
        se.add(p2);
        se.add(p3);
        System.out.println(se);
    }
}

 

 

 

 

你可能感兴趣的:(JAVA知识,Java)