HashSet底层HashMap的value为何是PRESENT?

HashSet底层的HashMap所存的value为什么不是null?而是一个静态常量PRESENT?

HashSet底层add方法

底层源码

public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

可以看出底层是调用了HashMap的put方法,我们知道HashMap的put方法的返回值为null或者value。如果put成功的话返回null,如果put失败的话,说明put的key已经存在了,就会返回已经存在该key的value值。例如

 public static void main(String[] args) {
        HashMap map=new HashMap(5);
        map.put("1","one");
        map.put("2","two");
        Object three = map.put("3", "three");
        Object four = map.put("3", "four");
        System.out.println(three);
        System.out.println(four);
    }

结果:

null    //put成功,返回null
three   //put失败,返回hashmap中该key所对应的value

此时再回过头看hashset的add方法,如果底层hashmap的value保存的是null的话,那么put成功或者失败都会返回null,那么HashSet的add()方法每次返回的布尔值都是true了,也就不能够确认add成功还是失败了。

HashSet底层remove方法

底层源码

 public boolean remove(Object o) {
        return map.remove(o)==PRESENT;
    }

底层是调用了了HashMap的remove方法,我们知道hashmap的remove方法会返回该key对应的value值。例如:

public static void main(String[] args) {
        HashMap map=new HashMap(5);
        map.put("1","one");
        map.put("2","two");
        Object one = map.remove("1");
        Object three = map.remove("3");
        System.out.println("one:"+one);
        System.out.println("three:"+three);
    }

结果:

one:one   //remove成功返回对应的value值
three:null //remove失败返回null

这时候再回头看也能看出一些问题,如果HashMap底层的value保存的都是null的话,那么remove成功或者是失败都会返回null,这时候就会出现与add同样无法区分的问题,无法区分remove是成功还是失败了!

  • 16
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值