public class demo1 {
public static void main(String[] args) {
HashSet set1 = new HashSet<>();
set1.add(“hello”);
set1.add(“java”);
set1.add(“hive”);
set1.add(“flume”);
set1.add(“hello”);
set1.add(“hive”);
for(String s : set1){
System.out.println(s);
}
}
}
结果为
会发现这里成功的去重了,元素是唯一且无序的
2. 集合添加的元素是自定义对象时
那么再来看看将自定义对象传入Set集合会怎么样
import java.util.HashSet;
public class demo2 {
public static void main(String[] args) {
HashSet set = new HashSet<>();
Student s1 = new Student(“zhang”,12);
Student s2 = new Student(“chen”,20);
Student s3 = new Student(“cao”,60);