您的位置:首页 > 编程语言 > Java开发

关于jdk HashSet 源码

2011-03-04 20:29 85 查看
以前一直纠结HashMap和HashSet有什么区别,还老爱忘记。很难记
看了jdk的HashSet实现,才感觉有点意思了


public HashSet() {
map = new HashMap<E,Object>();
}

这是HashSet的一个无参构造,很显然一个HashSet就是一个特殊的HashMap,特殊在哪儿呢?key很特殊,它是一个HashMap但Key却是由HashSet管理的:

/**
* 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;
}

原来在集合里使用key来存储集合元素,这就解释了为什么HashSet不能有重复元素之说了,
细心一下,那这个特殊的map的value干嘛去了呢?PRESENT是个什么东西呢?

// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

又是一个不解风情的东西,原来jdk里也用对象来占位的东西啊 :?: 阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: