常用容器(Collection)实现类总结(四)——HashSet

HashSet简略说明:

此类实现 Set 接口,由哈希表(实际上是一个 HashMap 实例)支持。它不保证 set 的迭代顺序;特别是它不保证该顺序恒久不变。此类允许使用 null 元素。

(This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. )

 

(注意:HashSet必须重写hashcode和equals方法)

 

HashSet的优、缺点分析:

优点:

  • 不允许储存相同的对象(注意:HashSet使用成员对象来计算hashcode值,对于两个对象来说hashcode可能相同,所以equals()方法用来判断对象的相等性,如果两个对象不同的话,那么返回false)

缺点:

  • 相较HashMap速度慢(HashMap由唯一的Key来找Value)

 

 

方法分析:

HashSet的底层实现实际上是HashMap,主要分析其中一个方法add():

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

可见,传入的形参e是作为map的Key,而HashSet的元素不可重复实际上就是利用了Map中Key的不可重复

再看看PRESENT是什么:

private static final Object PRESENT = new Object();

定义一个虚拟的Object对象作为HashMap的value,将此对象定义为static final

posted @ 2017-03-28 20:48  NOthingAJ  阅读(187)  评论(0编辑  收藏  举报