标签:new rem collect 哈希表 可重复 ack actual 容器 顺序
此类实现 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的底层实现实际上是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
常用容器(Collection)实现类总结(四)——HashSet
标签:new rem collect 哈希表 可重复 ack actual 容器 顺序
原文地址:http://www.cnblogs.com/nothingAJ/p/6636778.html