2010-02-12 63 views

回答

5

的关键将是走进了HashSet的本身,因为对象地图的关键是集合。

+0

当你说“地图的钥匙是套”时,你是什么意思? – danben 2010-02-12 05:47:42

+2

地图的一个键总是会映射到相同的值,所以所有的地图键都必须是唯一的。所以根据定义,它们是集合。 – 2010-02-12 05:54:35

+0

或者如果你看看Map.keySet(),它会返回一个Set。 – 2010-09-14 20:58:37

6

从来源:

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


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

有趣;我一直认为它会放(e,e)。 – 2010-02-12 08:03:33

+0

为什么不只是使用空值? – dertoni 2010-08-03 13:07:03

+2

@dertoni:当然,我没有写它,但我的猜测是他们想要允许HashMap的不同支持实现,这将不保证允许空值。 – danben 2010-08-03 14:40:38

1

的想法是使用您添加到HashSet作为HashMap的主要对象。这样在O(1)中运行add,removecontains

0

是(source code here)。 HashSet实质上是一个HashMap的keySet的接口。

/** 
    * HashSet is an implementation of a Set. All optional operations (adding and 
    * removing) are supported. The elements can be any objects. 
    */ 
    public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, 
      Serializable { 

     private static final long serialVersionUID = -5024744406713321676L; 

     transient HashMap<E, HashSet<E>> backingMap; // right here!