创建一个Person类
package com.sean.base.SetStudy; /** * * @create 2021-02-25 14:43 */ 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 + ‘}‘; } }
package com.sean.base.SetStudy; import java.util.HashSet; /** HashSet的使用 * 存储结构:哈希表(数组+链表+红黑树) * @create 2021-02-25 14:42 */ public class Demo03 { public static void main(String[] args) { //创建集合 HashSet<Person> persons = new HashSet<Person>(); //1添加数据 Person p1 = new Person("刘德华",20); Person p2 = new Person("林志玲",25); Person p3 = new Person("郭德纲",23); persons.add(p1); persons.add(p2); persons.add(p3); System.out.println("元素个数:"+persons.size()); System.out.println(persons.toString()); } }
原文:https://www.cnblogs.com/guangenpu/p/14446918.html