• Map和Set



    目录

    🥬Map

    🍌Map常用方法的使用

    🥬Set

    🍌Set常用方法的使用

    🌲例题

    🥬二叉搜索树

    🥬哈希表

     🍌哈希冲突

    🍌避免冲突

    🥬小结


    🥬Map

    Map 是一个接口类,该类没有继承自 Collection ,该类中存储的是 <K,V> 结构的键值对,并且 K 一定是唯一的,不能重复

    🍌Map常用方法的使用

    1、V put(K key, V value)   //设置 key 对应的 value

    1. map.put(1,"hello");
    2. map.put(2,"world");
    3. //结果:{1=hello, 2=world}

    2、V get(Object key)   //返回 key 对应的 value

    1. map.get(1);
    2. //结果:hello

    3、V getOrDefault(Object key, V defaultValue)   //返回 key 对应的 valuekey 不存在,返回默认值

    1. String str=map.getOrDefault(2,"hi");
    2. String str1=map.getOrDefault(3,"hi");
    3. //结果:
    4. //str world
    5. //str1 hi

    4、V remove(Object key)   //删除 key 对应的映射关系

    1. map.remove(1);
    2. System.out.println(map);
    3. //结果:{2=world}

    5、Set<K> keySet() 返回所有 key 的不重复集合

    1. map.put(1,"hi");
    2. map.put(2,"thanks");
    3. map.put(2,"what");
    4. map.put(3,"how");
    5. System.out.println(map.keySet());
    6. //结果:[1, 2, 3]

    6、Set<Map.Entry<K, V>> entrySet()   //返回所有的 key-value 映射关系

    1. map.put(1,"hi");
    2. map.put(2,"thanks");
    3. map.put(3,"how");
    4. for(Map.Entry<Integer, String> entry : map.entrySet()){
    5. System.out.println(entry.getKey() + "--->" + entry.getValue());
    6. }
    7. System.out.println();
    8. //结果:
    9. 1--->hi
    10. 2--->thanks
    11. 3--->how

    7、boolean containsKey(Object key)   //判断是否包含 key

         boolean containsValue (Object value)   //判断是否包含 value
    1. map.put(1,"hi");
    2. map.put(2,"thanks");
    3. map.put(3,"how");
    4. map.containsKey(1);//true
    5. map.containsKey(5);//false
    6. map.containsValue("hi");//true
    7. map.containsValue("hello");//false
    补充说明:Map.Entry<K, V> Map 内部实现的用来存放 <key, value> 键值对映射关系的内部类 ,该内部类中主要提供了 <key, value> 的获取, value 的设置以及Key的比较方式。使用Map.Entry类,你可以得到在同一时间得到所有的信息 (注意:Map.Entry<K,V> 并没有提供设置 Key 的方法 )
    1. K getKey() //返回 entry 中的 key
    2. V getValue() //返回 entry 中的 value
    3. V setValue(V value) //将键值对中的value替换为指定value

    注意:

    1. Map 是一个接口,不能直接实例化对象 如果 要实例化对象只能实例化其实现类 TreeMap 或者 HashMap 。

    2. Map中存放键值对的Key是唯一的,value是可以重复的 。

    3. 在 Map 中插入键值对时, key 不能为空,否则就会抛 NullPointerException 异常 ,但是 value可以为空 。

    4. Map中的Key可以全部分离出来,存储到Set来进行访问(因为Key不能重复)。

    5. Map中的value可以全部分离出来,存储在Collection的任何一个子集合中(value可能有重复)。

    6. Map中键值对的 Key 不能直接修改, value 可以修改,如果要修改 key ,只能先将该 key删除掉,然后再来进行 重新插入。

    🥬Set

    Set Map 主要的不同有两点: Set 是继承自 Collection 的接口类, Set 中只存储了 Key

    🍌Set常用方法的使用

    1、boolean add(E e)   //添加元素,但重复元素不会被添加成功

    1. Set<Integer> set=new HashSet<>();
    2. set.add(1);
    3. set.add(2);
    4. set.add(3);
    5. boolean flg=set.add(1);
    6. System.out.println(flg);
    7. System.out.println(set);
    8. //结果
    9. //false
    10. //[1, 2, 3]

    2、boolean contains(Object o)   //判断 o 是否在集合中

    1. boolean flg=set.contains(1);//true
    2. boolean flg1=set.contains(6);//false

    3、Iterator<E> iterator()   //返回迭代器

    1. set.add(1);
    2. set.add(2);
    3. set.add(3);
    4. Iterator it= set.iterator();
    5. while(it.hasNext()){
    6. System.out.print(it.next()+" ");
    7. }
    8. //结果:1 2 3

    4、boolean remove(Object o)  //删除集合中的 o

    1. set.add(1);
    2. set.add(2);
    3. set.add(3);
    4. boolean flg2=set.remove(1);
    5. System.out.println(flg2);//true
    6. System.out.println(set);//[2, 3]

    5、int size()  //返回set中元素的个数

    1. set.add(1);
    2. set.add(2);
    3. set.add(3);
    4. System.out.println(set.size());//3

    6、boolean isEmpty()   //检测set是否为空,空返回true,否则返回false

    7、Object[] toArray()   //将set中的元素转换为数组返回

    1. Set<Object> set1=new HashSet<>();
    2. Object[] array1=set1.toArray();
    3. Set<Integer> set2=new HashSet<>();//指定类型
    4. Integer[] array=set2.toArray(new Integer[0]);
    注意:
    1. Set 是继承自 Collection 的一个接口类
    2. Set 中只存储了 key ,并且要求 key 一定要唯一
    3. Set 的底层是使用 Map 来实现的,其使用 key Object 的一个默认对象作为键值对插入到 Map 中的
    4. Set 最大的功能就是对集合中的元素进行去重

    5. 实现Set接口的常用类有TreeSetHashSet,还有一个LinkedHashSetLinkedHashSet是在HashSet的基础 上维护了一个双向链表来记录元素的插入次序。

    6. Set 中的 Key 不能修改,如果要修改,先将原来的删除掉,然后再重新插入 。
    7. Set 中不能插入 null key

    🌲例题

    1、在1_0000个数据里面找重复的数据

    1. public static Map<Integer,Integer> func(int[] array){
    2. //判断array中的元素是否在map中,如果不在就是1,如果在就在原来的基础上加1
    3. Map<Integer,Integer> map=new HashMap<>();
    4. for(int x:array){
    5. if(map.get(x)==null){
    6. map.put(x,1);
    7. }else{
    8. int val=map.get(x);
    9. map.put(x,val+1);
    10. }
    11. }
    12. return map;
    13. }
    14. public static void main(String[] args) {
    15. int[] array=new int[10000];
    16. Random random=new Random();
    17. for(int i=0;i< array.length;i++){
    18. array[i]=random.nextInt(1000);//生成的随机数在0-1000之间,一定有重复的元素
    19. }
    20. Map<Integer,Integer> map=func(array);
    21. System.out.println(map);
    22. String str="array";
    23. System.out.println(str.toCharArray());
    24. }

    2、将10000个数据去重

    1. public static Set<Integer> func(int[] array){
    2. Set<Integer> set=new HashSet<>();
    3. for (int x:array) {
    4. set.add(x);
    5. }
    6. return set;
    7. }
    8. public static void main(String[] args) {
    9. int[] array=new int[10000];
    10. Random random=new Random();
    11. for (int i = 0; i < array.length; i++) {
    12. array[i]=random.nextInt(1000);
    13. }
    14. Set<Integer> set=func(array);
    15. System.out.println(set);
    16. int ret=func1(array);
    17. System.out.println(ret);
    18. }

    🥬二叉搜索树

    二叉搜索树又称二叉排序树,它或者是一棵空树 ,或者是具有以下性质的二叉树
    若它的左子树不为空,则左子树上所有节点的值都小于根节点的值
    若它的右子树不为空,则右子树上所有节点的值都大于根节点的值
    它的左右子树也分别为二叉搜索树

     🍌查找

     在二叉搜索树中查找某个值key,就用key和根节点比较,key更大,在右子树查找,key更小,在左子树查找。

    代码示例:

    1. public Node search(int key){
    2. Node cur=root;
    3. while(cur!=null){
    4. if(key>cur.val){
    5. cur=cur.right;
    6. }else if(key<cur.val){
    7. cur=cur.left;
    8. }else{
    9. return cur;
    10. }
    11. }
    12. return null;//没找到
    13. }

    🍌插入

    在二叉搜索树中插入某个结点,要不破坏它的性质,所以要先找到合适插入的位置,然后再插入

    1. public boolean insert(int val){
    2. //空树情况下
    3. if(root==null){
    4. root=new Node(val);
    5. return true;
    6. }
    7. //找到要插入的位置
    8. Node cur=root;
    9. Node parent=null;//记录父节点
    10. while(cur!=null) {
    11. if (val > cur.val) {
    12. parent = cur;
    13. cur = cur.right;
    14. } else if (val < cur.val) {
    15. parent = cur;
    16. cur = cur.left;
    17. } else {
    18. return false;//不能有相同数据
    19. }
    20. }
    21. //插入
    22. Node tmp=new Node(val);
    23. if(val<parent.val){
    24. parent.left=tmp;
    25. }else{
    26. parent.right=tmp;
    27. }
    28. return true;
    29. }

    🍌删除

    删除二叉搜索树中某个结点,先找到要删除的位置,在进行删除

     代码示例:

    1. public void remove(int key){
    2. Node cur=root;
    3. Node parent=null;
    4. //找到要删除结点位置
    5. while(cur!=null){
    6. if(cur.val==key){
    7. removeNode(cur,parent);
    8. break;
    9. }else if(cur.val<key){
    10. parent=cur;
    11. cur=cur.right;
    12. }else{
    13. parent=cur;
    14. cur=cur.left;
    15. }
    16. }
    17. }
    18. //删除
    19. public void removeNode(Node cur,Node parent){
    20. if(cur.left==null){
    21. if(cur==root){
    22. root=cur.right;
    23. }else if(cur==parent.left){
    24. parent.left=cur.right;
    25. }else if(cur==parent.right){
    26. parent.right=cur.right;
    27. }
    28. }else if(cur.right==null){
    29. if(cur==root){
    30. root=root.left;
    31. }else if(cur==parent.left){
    32. parent.left=cur.left;
    33. }else if(cur==parent.right){
    34. parent.right=cur.left;
    35. }
    36. }else{
    37. //右数找最小值,左数找最大值
    38. Node targetParent=cur;
    39. Node target=cur.right;
    40. while(target.left!=null){
    41. targetParent=target;
    42. target=target.left;
    43. }
    44. //找到了右树最小值
    45. cur.val=target.val;
    46. if(target==targetParent.left){
    47. targetParent.left=target.right;
    48. }else{
    49. targetParent.right=target.left;
    50. }
    51. }
    52. }

    🥬哈希表

    顺序结构以及平衡树 中,元素关键码与其存储位置之间没有对应的关系,因此在 查找一个元素时,必须要经过关键码的多次比较 顺序查找时间复杂度为 O(N) ,平衡树中为树的高度,即 O( log2^N
    ) ,搜索的效率取决于搜索过程中 元素的比较次数。
    理想的搜索方法:可以 不经过任何比较,一次直接从表中得到要搜索的元素。  如果构造一种存储结构,通过某种函数(hashFunc)使元素的存储位置与它的关键码之间能够建立一一映射的关系,那么在查找时通过该函数可以很快找到该元素。
    当向该结构中:
    插入元素
    根据待插入元素的关键码,以此函数计算出该元素的存储位置并按此位置进行存放 。
    搜索元素
    对元素的关键码进行同样的计算,把求得的函数值当做元素的存储位置,在结构中按此位置取元素比较,若关键码相等,则搜索成功。
    该方式即为哈希( 散列 ) 方法, 哈希方法中使用的转换函数称为哈希 ( 散列 ) 函数,构造出来的结构称为哈希表(Hash Table)(或者称散列表)。

     🍌哈希冲突

    当一个哈希函数为: hash(key) = key % capacity ;( capacity 为存储元素底层空间总的大小)

    我们可以看到4和14通过相同哈希函数找到了相同的位置,发生了冲突。

    此时不同的关键字通过相同的哈希函数有可能找到相同的位置。此时的情况就叫: 哈希冲突/哈希碰撞。

    🍌避免冲突

    首先,我们需要明确一点,由于我们哈希表底层数组的容量往往是小于实际要存储的关键字的数量的,这就导致一个问题, 冲突的发生是必然的 ,但我们能做的应该是尽量的 降低冲突率。
    💧哈希函数设计
    引起哈希冲突的一个原因可能是: 哈希函数设计不够合理 哈希函数设计原则
    1.哈希函数的定义域必须包括需要存储的全部关键码,而如果散列表允许有 m 个地址时,其值域必须在 0 m-1 之间
    2.哈希函数计算出来的地址能均匀分布在整个空间中
    3.哈希函数应该比较简单
    常见哈希函数
    1. 直接定制法 --( 常用 )
    取关键字的某个线性函数为散列地址: Hash Key = A*Key + B 优点:简单、均匀。缺点:需要事先知道关键字的分布情况。使用场景:适合查找比较小且连续的情况。
    2. 除留余数法 --( 常用 )
    设散列表中允许的 地址数为 m ,取一个不大于 m ,但最接近或者等于 m 的质数 p 作为除数,按照哈希函数:Hash(key) = key% p(p<=m), 将关键码转换成哈希地址 。
    💧负载因子调节

    散列表的载荷因子定义为: a =填入表中的元素个数/散列表的长度。
    a是散列表装满程度的标志因子。由于表长是定值,a与“填入表中的元素个数”成正比,所以,a越大,表明填入表中的元素越多,产生冲突的可能性就越大。反之,a越小,标明填入表中的元素越少,产生冲突的可能性就越小。实际上,散列表的平均查找长度是载荷因子a的函数,只是不同处理冲突的方法有不同的函数。对于开放定址法,荷载因子是特别重要因素,应严格限制在0. 7-0.8以下。超过0.8,查表时的CPU缓存不命中( cachemissing)按照指数曲线上升。因此,一些采用开放定址法的hash库,如Java的系统库限制了荷载因子为0.75,超过此值将resize散列表。

    随着负载因子的增大,冲突率也在增大,所以当冲突率达到一个无法忍受的程度时,我们需要通过降低负载因子来变相的降低冲突率。已知哈希表中已有的关键字个数是不可变的,那我们能调整的就只有哈希表中的数组的大小。

    解决哈希冲突 两种常见的方法是: 闭散列 开散列

    🌵闭散列

    也叫开放定址法,当发生哈希冲突时,如果哈希表未被装满,说明在哈希表中必然还有空位置,那么可以把 key 存放到冲突位置中的 下一个 空位置中去。 那如何寻找下一个空位置呢?
    比如上面的场景,现在需要插入元素 14 ,先通过哈希函数计算哈希地址,下标为 4 ,因此 14 理论应该插在该 位置,但是该位置已经放了值为 4 的元素,即发生哈希冲突。这时我们可以进行线性探测找到下一个位置。
    线性探测:从发生冲突的位置开始,依次向后探测,直到寻找到下一个空位置为止。

     但是线性探测有一个不好的地方,它依次向后探测,直到寻找到下一个空位置为止,如果空位置是连续的那么产生冲突的元素都放在一起了。

    🌵开散列

    开散列法(哈希桶)又叫链地址法 ( 开链法 ),首先对关键码集合用散列函数计算散列地址,具有相同地址的关键码归于同一子集合,每一个子集合称为一个桶,各个桶中的元素通过一个单链表链接起来,各链表的头结点存储在哈希表中。开散列,可以认为是把一个在大集合中的搜索问题转化为在小集合中做搜索了。

     💧实现

    1. public class HashBuck {
    2. static class Node{
    3. public int key;
    4. public int val;
    5. Node next;
    6. public Node(int key,int val){
    7. this.key=key;
    8. this.val=val;
    9. }
    10. }
    11. public Node[] array;
    12. public int usedSize;
    13. public static final double DEFAULT_LOAD_FACTOR = 0.75;//负载因子
    14. public HashBuck(){
    15. this.array=new Node[10];
    16. }
    17. /**
    18. * put函数
    19. * @param key
    20. * @param val
    21. */
    22. public void put(int key,int val){
    23. //1、确认key所在位置
    24. int index=key% array.length;
    25. Node cur=array[index];
    26. //2、遍历这个下标的链表,看是不是有相同的key,有的话要更新val值
    27. while(cur!=null){
    28. if(cur.key==key){
    29. cur.val=val;
    30. return;
    31. }
    32. cur=cur.next;
    33. }
    34. //3、没有key这个元素,用头插法插入
    35. Node node=new Node(key,val);
    36. node.next=array[index];
    37. array[index]=node;
    38. this.usedSize++;
    39. //4、插入元素成功之后,检查当前散列表的负载因子
    40. if(loadFactor()>=DEFAULT_LOAD_FACTOR){
    41. resize();//扩容
    42. }
    43. }
    44. private void resize(){
    45. Node[] newArray=new Node[array.length*2];
    46. for(int i=0;i< newArray.length;i++){
    47. Node cur=newArray[i];
    48. while(cur!=null){
    49. int index= cur.key% newArray.length;//获取新下标
    50. //就是把cur这个节点,以头插的形式 插入到新的数组对应下标的链表当中
    51. Node curNext=cur.next;
    52. cur.next=newArray[index];
    53. newArray[index]=cur;
    54. cur=curNext;
    55. }
    56. }
    57. array=newArray;
    58. }
    59. private double loadFactor() {
    60. return 1.0*usedSize/ array.length;
    61. }
    62. /**
    63. * 根据key获得val值
    64. * @param key
    65. * @return
    66. */
    67. public int get(int key){
    68. //1、确认key所在位置
    69. int index=key% array.length;
    70. Node cur=array[index];
    71. //2、遍历这个下标的链表,找到key,返回当前val值
    72. while(cur!=null){
    73. if(cur.key==key){
    74. return cur.val;
    75. }
    76. cur=cur.next;
    77. }
    78. return -1;
    79. }
    80. }
    java 中计算哈希值实际上是调用的类的 hashCode 方法,进行 key 的相等性比较是调用 key equals 法。所以如果要用自定义类作为 HashMap key 或者 HashSet 的值, 必须重写 hashCode equals ,而且要做到 equals 相等的对象,hashCode 一定是一致的,但是hashCode相等的两个对象,equals不一定相等。
    代码示例:
    1. class Person{
    2. public String ID;
    3. public Person(String ID){
    4. this.ID=ID;
    5. }
    6. //重写
    7. @Override
    8. public boolean equals(Object o) {
    9. if (this == o) return true;
    10. if (o == null || getClass() != o.getClass()) return false;
    11. Person person = (Person) o;
    12. return Objects.equals(ID, person.ID);
    13. }
    14. @Override
    15. public int hashCode() {
    16. return Objects.hash(ID);
    17. }
    18. @Override
    19. public String toString() {
    20. return "Person{" +
    21. "ID='" + ID + '\'' +
    22. '}';
    23. }
    24. }
    25. public class HashBuck2<K,V> {
    26. static class Node<K,V>{
    27. public K key;
    28. public V val;
    29. public Node<K,V> next;
    30. public Node(K key,V val){
    31. this.key=key;
    32. this.val=val;
    33. }
    34. }
    35. public Node<K,V>[] array=( Node<K,V>[])new Node[10];
    36. int usedSize;
    37. /**
    38. * put函数
    39. * @param key
    40. * @param val
    41. */
    42. public void put(K key,V val){
    43. int hash=key.hashCode();
    44. int index=hash% array.length;
    45. Node<K,V> cur=array[index];
    46. while(cur!=null){
    47. //利用equals进行相等性比较
    48. if(cur.key.equals(key)){
    49. cur.val=val;
    50. return;
    51. }
    52. cur=cur.next;
    53. }
    54. Node<K,V> node=new Node<>(key,val);
    55. node.next=array[index];
    56. array[index]=node;
    57. this.usedSize++;
    58. }
    59. /**
    60. * 根据key获得val值
    61. * @param key
    62. * @return
    63. */
    64. public V get(K key){
    65. int hash=key.hashCode();
    66. int index=hash% array.length;
    67. Node<K,V> cur=array[index];
    68. while(cur!=null){
    69. if(cur.key.equals(key)){
    70. return cur.val;
    71. }
    72. cur=cur.next;
    73. }
    74. return null;
    75. }

    常见问题:(看源码)

    1.如果new HashMap(19), bucket数组多大?
          >=19 &&最接近19的一个2次幂--32
    2. HashMap什么时候开辟bucket数组占用内存?
          第一次put的时候--16
    3. hashMap何时扩容?
          超过负载因子的时候扩容,且是2倍扩容的
    4.当两个对象的hashcode相同会发生什么?
          冲突
    5.如果两个键的hashcode相同,你如何获取值对象?
          遍历与hashCode值相等时相连的链表,直到相等(equals)或者null(没有找到)
    6.你了解重新调整HashMap大小存在什么问题吗?
          重新哈希原来的元素到新的链表当中

    🥬小结

    以上就是今天的内容了,有什么问题都可以在评论区留言哦✌✌✌

  • 相关阅读:
    PHP mysqli 增强 批量执行sql 语句的实现代码
    Jetpack Compose学习(11)——Navigation页面导航的使用
    网络中的一些基本概念
    1.1 数据采集总览
    c语言内存函数
    GO语言-锁操作
    四、kotlin的可空性和基本数据类型
    Linux——常用命令(2)
    Docker Hub 镜像代理加速
    小米手机便签怎么导出到华为mate60Pro手机上?
  • 原文地址:https://blog.csdn.net/m0_65673419/article/details/125128866