探究 HashSet - add 方法

无意中得知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来排序 若类中不存在 则抛出异常!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值