zoukankan      html  css  js  c++  java
  • 探究 HashSet

    无意中得知HashSet中不允许添加重复值这个原理 内部是用Map的映射写的  我们可进入HashSet中的add 查看  详细如下:

    跟踪Add方法进去:

    
    
    /*Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.
    Params:
    e – element to be added to this set
    Returns:
    true if this set did not already contain the specified element*/
    public boolean add(E e) {
    return map.put(e, PRESENT)==null;
    }

    map.put 是吧 
     可以看到add(E e)方法本身调用了map.put()方法,而我们再查看map可以发现map其实是一个全局变量

    而这个全局变量指向的是HashSet里的HashMap对象,

    不想写 更多自己去研究吧

    总结就是:为什么要重写 hashcode 和 equal  咯,懂得它的原理,其实还蛮好。

    这里再讲一遍: hashset 和 treeset 的 add 方法是内部是不一样的  treeset的add 是会调用compareTo来排序 若类中不存在 则抛出异常!

    本文来自博客园,作者:咸瑜,转载请注明原文链接:https://www.cnblogs.com/bi-hu/p/14689609.html

  • 相关阅读:
    python笔记---@classmethod @staticmethod
    python笔记--socket编程
    python笔记--异常处理
    WebStorm 配置
    ECS node 环境搭建
    spm + host
    Untuntu的apt 终端命令
    Ubuntu 添加至启动栏
    Ubuntu设置镜像源
    Ubuntu 设置中文语言环境
  • 原文地址:https://www.cnblogs.com/bi-hu/p/14689609.html
Copyright © 2011-2022 走看看