我们知道Set集合中是没有重复元素的,而HashMap中没有重复的key,HashMap的key集合是一个Set对象...
打开HashSet源码,果然,里面有map对象...
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
static final long serialVersionUID = -5024744406713321676L;
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<>();
}
}
PRESENT是一个dummy值,用于填充map的value值,key值才是HashSet实现没有重复元素的关键,这一切都隐藏在HashSet中的add方法.
/**
* 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 如果集合中已经存在该元素,则返回true.
*/
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
可以看到,map中放入了一个key为e,value为PRESENT的对象...所以说,value一直都是同一个对象,真正用到的只有key值.
简单的来说,HashSet使用HashMap的key值唯一的特性实现的.