【1】放入Integer类型数据
package com.msb.test06;import java.util.HashSet;/*** @author : liu* 日期:10:36:57* 描述:IntelliJ IDEA* 版本:1.0*/ public class TestInteger {//这是一个main方法:是程序的入口public static void main(String[] args) {//创建一个HashSet集合HashSet<Integer> hs = new HashSet<>();System.out.println(hs.add(19));//truehs.add(5);hs.add(20);System.out.pringln(hs.add(19));//false没有被写入集合hs.add(41);hs.add(0);System.out.println(hs.size());//唯一 无序 System.out.println(hs);} }
【2】放入String类型数据
package com.msb.test06;import java.util.HashSet;/*** @author : liu* 日期:10:41:10* 描述:IntelliJ IDEA* 版本:1.0*/ public class TestString {//这是一个main方法:是程序的入口public static void main(String[] args) {HashSet<String> hs=new HashSet<>();hs.add("hello");hs.add("apple");hs.add("banana");hs.add("html");hs.add("apple");hs.add("css");System.out.println(hs.size());System.out.println(hs);} }
【3】放入自定义引用数据类型的数据
package com.msb.test06;import java.util.HashSet;/*** @author : liu* 日期:10:48:02* 描述:IntelliJ IDEA* 版本:1.0*/ 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());System.out.println(hs);} }
上面自定义的类型不满足唯一、无序类型数据的特点。为什么呢?
【4】HashSet原理图:(简要原理图)
package com.msb.test06;import java.util.Objects;/*** @author : liu* 日期:10:47:02* 描述:IntelliJ IDEA* 版本:1.0*/ 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;}@Overridepublic String toString() {return "Student{" +"age=" + age +", name='" + name + '\'' +'}';}public Student(int age, String name) {this.age = age;this.name = name;}@Overridepublic 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);}@Overridepublic int hashCode() {return Objects.hash(age, name);} }