(1)Set集合
Set也是集合中的一个容器,程序可以依次把若干个对象放进Set,但是Set无法保存元素添加的顺序, Set不允许包含相同的元素,如果把两个相同的元素加入同一个Set中,则添加失败,add()方法会返回false,并且新元素不会被添加。
(2)HashSet
HashSet 是 Set 接口的典型实现,大多数时候使用 Set 集合时就是使用这个实现类。 HashSet 按 Hash算法来存储集合中的元素,因此具有很好的存取和查找性能。 特点:不能保证元素的排列顺序,顺序可能与添加顺序不同,顺序也有可能发生变化。HashSet 不是同步的,如果多个线程同时访问一个 HashSet,假设有两个或者两个以上线程同时修改了HashSet集合时,则必须通过代码来保证其同步。集合元素值可以是 null。当向 HashSet 集合中存入一个元素时,HashSet 会调用该对象的 hashCode()方法来得到该对象的 hashCode 值,然后根据该hashCode 值决定该对象在 HashSet 中的存储位置。如果有两个元素通过equals()方法比较返回 true,但它们的 hashCode()方法返回值不相等,HashSet 将会把它们存储在不同的位置,依然可以添加成功。也就是说,HashSet 集合判断两个元素相等的标准是两个对象通过 equals()方法比较相等,并且两个对象的 hashCode()方法返回值也相等。 常用Api
public class Test2 { public static void main(String[] args) { Set<String> set = new HashSet<>(); //添加元素 set.add("秦始皇"); set.add("唐太宗"); set.add("武则天"); //移除元素 System.out.println(set.remove("贞观之治")); //获取元素个数 System.out.println(set.size()); //判断是否空集合 System.out.println(set.isEmpty()); // for (String s:set) { // System.out.println(s); // } // Iterator<String> it = set.iterator(); // while (it.hasNext()){ // System.out.println(it.next()); // } set.forEach(e-> System.out.println(e)); } }
public class Test { public static void main(String[] args) { Set<Student> set = new HashSet<>(); Student s1 = new Student("小明",18); Student s2 = new Student("小明",18); Student s3 = new Student("小明",19); set.add(s1); System.out.println(set.add(s2));//false System.out.println(set.add(s3));//true
}
}
HashSet的特点可以知道HashSet中存放的元素不能重复,利用这个特性就可以做一些去重的业务 输入一个字符串,统计字符串中出现的字符及数量
public class HashSetDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入字符串:"); String s = sc.next(); char [] chars =s.toCharArray(); Set<Character> set = new HashSet<>(); Map<Character,Integer> map = new HashMap<>(); for(int i = 0;i<chars.length-1;i++){ if(set.add(chars[i])){ map.put(chars[i], 1); }else{ Integer k = map.get(chars[i]); map.put(chars[i],k+1); } } map.forEach((key,value)->System.out.println(key+"==================="+value)); } }
重写equals 和 HashCode 方法 public class Student { public String name; public int age;
public Student(String name,int age){this.name = name;this.age = age; } @Override public boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Student student = (Student) o;//Objects工具类下的equals和hash方法比较常用,后期使用较多return age == student.age && Objects.equals(name, student.name); } @Override public int hashCode() {return Objects.hash(name, age); }
}