Student类如下所示:
package com.test.Test07; import java.util.Objects; public class Student { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Student{" + "age=" + age + ", name='" + name + '\'' + '}'; } public Student(int age, String name) { this.age = age; this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return age == student.age && Objects.equals(name, student.name); } @Override public int hashCode() { return Objects.hash(age, name); } }
测试类如下所示:
package com.test.Test07; import java.util.HashSet; public class TestStudent { //这是一个main方法,是程序的入口 public static void main(String[] args) { //创建一个HashSet集合 HashSet<Student> hs = new HashSet<>(); hs.add(new Student(19,"lili")); hs.add(new Student(20,"lulu")); hs.add(new Student(18,"feifei")); hs.add(new Student(19,"lili")); hs.add(new Student(10,"nana")); System.out.println(hs.size()); // 5 System.out.println(hs); //[Student{age=18, name='feifei'}, Student{age=10, name='nana'}, Student{age=20, name='lulu'}, Student{age=19, name='lili'}, Student{age=19, name='lili'}] /* //现在就变成了4条数据,HashSet符合唯一性的特点了。 4 [Student{age=18, name='feifei'}, Student{age=19, name='lili'}, Student{age=20, name='lulu'}, Student{age=10, name='nana'}]*/ } }