特点 import java.util.HashSet; import java.util.Set; //set集合特点:1.没有索引 2.无序 3.不能存重复元素 public class Demo01 { public static void main(String[] args) { Set<String> set=new HashSet<>(); set.add("hello"); set.add("hello"); set.add("hi"); for(String s:set){ System.out.println(s);//hi hello } } } Hash表 import java.util.HashSet; import java.util.Set; //Hash表 初始容量16 加载因子0.75 public class Demo03 { public static void main(String[] args) { Set<String> set=new HashSet<>(); set.add("a"); set.add("b"); set.add("c"); set.add("c"); } } HashSet存储 public class Person { private String name; private int 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; } public Person(){} public Person(String name, int age) { super(); this.name = name; this.age = age; } public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } //点出来的 //重写hashCode方法 public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } //重写equals方法 public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } 存储API类型元素 public class Demo02 { public static void main(String[] args) { Person p1=new Person();//调用空参 System.out.println(p1.hashCode());//961 Person p2=new Person(); System.out.println(p2.hashCode());//961 String s1=new String("abc");//构造方法重写 String s2=new String("abc"); System.out.println(s1.hashCode());//96354 System.out.println(s2.hashCode());//96354 } } 存储自定义类型元素 import java.util.HashSet; import java.util.Set; public class Demo04 { public static void main(String[] args) { Set<Person> set=new HashSet<Person>(); set.add(new Person("a",10)); set.add(new Person("d",11)); set.add(new Person("c",12)); set.add(new Person("c",12)); for(Person p:set){ System.out.println(p);//Person [name=a, age=10] } //Person [name=c, age=12] } //Person [name=d, age=11] } LinkedHashSet import java.util.ArrayList; import java.util.LinkedHashSet; //有序set public class Demo05 { public static void main(String[] args) { LinkedHashSet<String> set=new LinkedHashSet<>(); set.add("hello"); set.add("hi"); set.add("lucky"); for(String s:set){ System.out.println(s); } } }