当前位置: 移动技术网 > IT编程>开发语言>Java > Core Java 简单谈谈HashSet(推荐)

Core Java 简单谈谈HashSet(推荐)

2019年07月19日  | 移动技术网IT编程  | 我要评论

同学们在看这个问题的时候,我先提出者两个问题,然后大家带着问题看这个文章会理解的更好。

1、hashset为什么添加元素时不能添加重复元素?

2、hashset是否添加null元素?

打开源码, 我们看到如下代码,我们看到hashset也有一个hashmap做为属性,hashset()的构造方法就是将这个map实例化。如果大家对hashmap还不了解话,可以看我的这篇博文。还要注意有一个静态final的对象present,这个是干什么用的,咱们继续往下看。

private transient hashmap<e,object> map;

 // dummy value to associate with an object in the backing map
 private static final object present = new object();

 /**
  * constructs a new, empty set; the backing <tt>hashmap</tt> instance has
  * default initial capacity (16) and load factor (0.75).
  */
 public hashset() {
  map = new hashmap<>();
 }

然后我们再打开其add方法,其就是将元素e放到hashmap中,然后将静态final对象present作为value放到里边,如果添加成功,那么hashmap返回null,然后也就是添加成功了,上一篇博文也讲到了,咱们再讲一次作为复习。如果将element放到hashmap里边,首先判断其hashcode,如果hashcode没有找到,就根据hashcode计算index放到对应的bucket中,如果hashcode相同的话,那么再根据key的是否equals作为第二判断,放到相应的linked list里边了。

/**
  * adds the specified element to this set if it is not already present.
  * more formally, adds the specified element <tt>e</tt> to this set if
  * this set contains no element <tt>e2</tt> such that
  * <tt>(e==null ? e2==null : e.equals(e2))</tt>.
  * if this set already contains the element, the call leaves the set
  * unchanged and returns <tt>false</tt>.
  *
  * @param e element to be added to this set
  * @return <tt>true</tt> if this set did not already contain the specified
  * element
  */
 public boolean add(e e) {
  return map.put(e, present)==null;

当然第二个问题同学们是否也想到了,因为hashmap是支持key为null的,所以hashset也是可以添加key为null的元素的。hashmap用的地方这么多,大家知道它很重要了吧?!

以上这篇core java 简单谈谈hashset(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网