package com.ITheima._set; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; public class SetDemo { public static void main(String[] args) { // 看看Set系列集合的特点: HashSet LinkedHashSet TreeSet // Set<String> sets=new HashSet<>();//一行经典代码 无序不重复 五索引 //Set<String> sets=new LinkedHashSet<>();//有序不重复 无索引 sets.add("HTML"); sets.add("MYSQL"); sets.add("Java"); sets.add("SpringBot"); System.out.println(sets);//[Java, MYSQL, HTML, SpringBot] } }View Code
package com.ITheima._set; public class SetDemo1 { public static void main(String[] args) { // 目标:学会获取对象的哈希值,并确认一下 String name = "itheima"; System.out.println(name.hashCode());//2118746965 System.out.println(name.hashCode());//2118746965 String name1 = "itheima1"; System.out.println(name1.hashCode());//1256646524 System.out.println(name1.hashCode());//1256646524 } }View Code
案例
Student类 重写 hasCode equals 方法
package com.ITheima._set; import java.util.Objects; public class Student { private String name; private int age; private char sex; public Student() { } public Student(String name, int age, char sex) { this.name = name; this.age = age; this.sex = sex; } 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 char getSex() { return sex; } public void setSex(char sex) { this.sex = sex; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", sex=" + sex + '}'; } @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 && sex == student.sex && Objects.equals(name, student.name); } @Override public int hashCode() { return Objects.hash(name, age, sex); } }View Code
SetDemo3类
package com.ITheima._set; import java.util.HashSet; import java.util.Set; /** * 目标:让Set集合把重复内容的对象去掉一个(去重复) */ public class SetDemo3 { public static void main(String[] args) { // Set集合去重复原因:先判断哈希值算出来的存储位置是否相同 再判断equals Set<Student> sets = new HashSet<>(); Student s1 = new Student("无恙", 20, '男'); Student s2 = new Student("无恙", 20, '男'); Student s3 = new Student("周雄", 21, '男'); //必须重写 hasCode equals 两个方法(才能保证不会出现重复) System.out.println(s1.hashCode());//685325104 System.out.println(s2.hashCode());//460141958 System.out.println(s3.hashCode());//1163157884 sets.add(s1); sets.add(s2); sets.add(s3); System.out.println(sets); } }View Code