2022.4.25 集合Set子接口及其实现类
Set子接口
特点:无序、无下标、元素不可重复
方法:全部继承自Collection中的方法
1 package com.xing.set; 2 3 import java.util.HashSet; 4 import java.util.Iterator; 5 import java.util.Set; 6 7 public class Demo01 { 8 public static void main(String[] args) { 9 //Set为接口,只能实例化其下面的实现类 10 Set<String> set = new HashSet<>();//后面<>里的内容可以不写 11 set.add("哈哈");//只能添加String类型 12 set.add("呵呵");//只能添加String类型 13 set.add("你好");//只能添加String类型 14 System.out.println(set.size()); 15 System.out.println(set); 16 17 //set.remove("哈哈");//不能通过角标删除 因为无序 18 19 //遍历 增强for 迭代器 20 Iterator<String> iterator = set.iterator(); 21 while (iterator.hasNext()) { 22 System.out.println(iterator.next()); 23 } 24 } 25 }
HashSet实现类 【重点】
存储结构:哈希表(数组+链表+红黑树)
1 package com.xing.set; 2 3 import java.util.HashSet; 4 import java.util.Set; 5 6 public class Demo02 { 7 public static void main(String[] args) { 8 HashSet<String> hashset = new HashSet<>();//后面<>里的内容可以不写 9 hashset.add("哈哈");//只能添加String类型 10 hashset.add("呵呵"); 11 hashset.add("你好"); 12 hashset.add("哈哈");//重复元素 不会输出 13 System.out.println(hashset.size()); 14 System.out.println(hashset); 15 16 //删除 清空 17 //hashset.remove("哈哈"); 18 19 //遍历 增强for 迭代器 20 21 //判断 22 } 23 } 24
存储过程(重复依据)
-
根据hashCode计算保存的位置,如果位置为空,直接保存,若不为空(说明存入元素重复),执行equals方法进行确认,如果equals为true,则认为是重复,拒绝存入,否则形成链表
1 package com.xing.set; 2 3 import java.util.HashSet; 4 import java.util.Objects; 5 import java.util.Set; 6 7 public class Demo02 { 8 public static void main(String[] args) { 9 Student s1 = new Student("张三",20); 10 Student s2 = new Student("李四",18); 11 Student s3 = new Student("王五",22); 12 13 HashSet<Student> hashset = new HashSet<>();//后面<>里的内容可以不写 14 hashset.add(s1); 15 hashset.add(s2); 16 hashset.add(s3); 17 //不重写方法能插入进去,因为重写了hashCode()与equals()方法 所以插入不进去 18 hashset.add(new Student("张三", 20)); 19 System.out.println(hashset.size()); 20 System.out.println(hashset);//必须重写toString才能打印 否则打印地址 21 22 //不重写方法不能删除,因为重写了hashCode()与equals()方法 可以删除 23 hashset.remove(new Student("张三", 20)); 24 } 25 } 26 27 class Student { 28 private String name; 29 private int age; 30 31 public Student() { 32 } 33 34 public Student(String name, int age) { 35 this.name = name; 36 this.age = age; 37 } 38 39 public String getName() { 40 return name; 41 } 42 43 public void setName(String name) { 44 this.name = name; 45 } 46 47 public int getAge() { 48 return age; 49 } 50 51 public void setAge(int age) { 52 this.age = age; 53 } 54 55 @Override 56 public int hashCode() { 57 int n1 = this.name.hashCode(); 58 int n2 = this.age; 59 return n1+n2; 60 } 61 62 @Override 63 public boolean equals(Object obj) { 64 //1 判断是不是同一个对象 65 if(this == obj){ 66 return true; 67 } 68 //2 判断是否为空 69 if(obj == null){ 70 return false; 71 } 72 //3 判断是否是Student类型 73 if(obj instanceof Student){ 74 Student s = (Student) obj; 75 //4 比较属性 76 if(this.name.equals(s.getName()) && this.age == s.getAge()){ 77 return true; 78 } 79 } 80 //5 不满足条件返回false 81 return false; 82 } 83 } 84