赞
踩
1、HashSet 实现了 Set 接口
2、HashSet 实际上是 HashMap
3、可以存放 null 值,但是只能有一个 null
4、HashSet 不保证元素是有序的,取决于hash后,再确定索引的结果
5、不能有重复元素/对象
- import java.util.HashSet;
- import java.util.Set;
-
- public class HashSet01 {
- public static void main(String[] args) {
- //1. 构造器的源码
- /*
- public HashSet() {
- map = new HashMap<>();
- }
- */
- //2. 可以存放null值,但是只能有一个,即元素不能重复
- Set hashSet = new HashSet();
- hashSet.add(null);
- hashSet.add(null);
- System.out.println(hashSet);
-
- //在执行add方法后,会返回一个boolean值
- //如果添加成功,返回true 否则返回false
- System.out.println(hashSet.add("张三"));//true
- System.out.println(hashSet.add("李四"));//true
- System.out.println(hashSet.add("老六"));//true
- System.out.println(hashSet.add("张三"));//false
- System.out.println(hashSet.add("铁蛋"));//true
-
- //可以通过remove指定删除哪个对象
- hashSet.remove("张三");
- System.out.println(hashSet);
-
- hashSet = new HashSet();
- hashSet.add("张三");//添加成功
- hashSet.add("张三");//添加失败
- hashSet.add(new Dog("小黑"));//添加成功
- hashSet.add(new Dog("小黑"));//添加成功
- System.out.println(hashSet);
-
- //经典面试题
- //看源码分析
- hashSet.add(new String("老六"));//加入成功
- hashSet.add(new String("老六"));//加入失败
- System.out.println(hashSet);
- }
- }
-
- class Dog {
- private String name;
-
- public Dog(String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return "Dog{" +
- "name='" + name + '\'' +
- '}';
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
分析 HashSet 底层是 HashMap,HashMap 底层是(数组+链表+ 红黑树)
- public class HashSetStructure {
- public static void main(String[] args) {
- //1. 创建一个数组,数组的类型是 Node[]
- //2. 有些人直接把 Node[] 数组称为 表
- Node[] table = new Node[16];
-
- //3. 创建节点
- Node zs = new Node("张三", null);
- table[2] = zs;//将节点存放到数组的索引2的位置
-
- Node ls = new Node("李四", null);
- zs.next = ls;//将ls 节点挂载到 zs
-
- Node ll = new Node("老六", null);
- ls.next = ll;//将ll 节点挂载到 ls
-
- Node td = new Node("铁蛋", null);
- table[3] = td;//将节点存放到数组的索引3的位置
- System.out.println(table);
- }
- }
-
- class Node {//节点,存储数据
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。