除了HashSet不允许重复值之外,HashMap和HashSet之间还有什么区别呢?

我是说执行方面?这有点模糊,因为两者都使用哈希表来存储值。


当前回答

HashSet是一个集合,例如{1,2,3,4,5}

HashMap是key ->值(键到值)映射,例如{a -> 1, b -> 2, c -> 2, d -> 1}

注意,在我上面的例子中,HashMap中不能有重复的键,但它可能有重复的值。

在HashSet中,必须没有重复的元素。

其他回答

HashSet是根据HashMap实现的。它是键和PRESENT对象之间的映射。

HashSet允许我们在集合中存储对象,而HashMap允许我们在键和值的基础上存储对象。每个对象或存储对象都有键。

它们之间的主要区别如下:

HashSet

它不允许重复密钥。 即使它不是同步的,这样也会有更好的性能。 它允许一个空键。 当您想要维护一个唯一的列表时,可以使用HashSet。 HashSet实现了Set接口,它是由哈希表(实际上是HashMap实例)支持的。 HashSet存储对象。 HashSet不允许重复元素,但允许空值。 该接口不能保证顺序随时间保持不变。

HashMap

It allows duplicate keys. It is not synchronized, so this will have better performance. HashMap does not maintain insertion order. The order is defined by the Hash function. It is not Thread Safe It allows null for both key and value. It allows one null key and as many null values as you like. HashMap is a Hash table-based implementation of the Map interface. HashMap store object as key and value pair. HashMap does not allow duplicate keys but null keys and values are allowed. Ordering of the element is not guaranteed overtime.

真可惜他们的名字都是以Hash开头的。这是最不重要的部分。重要的部分在哈希之后——集合和映射,正如其他人指出的那样。它们分别是Set(无序集合)和Map(有键访问的集合)。它们碰巧是用散列实现的——这就是名称的来源——但它们的本质隐藏在名称的这部分后面。

不要被他们的名字弄糊涂了;它们是完全不同的东西。

Hashset内部实现HashMap。如果您看到内部实现,则HashSet中插入的值将存储为HashMap中的键,并且该值是object类的Dummy对象。 HashMap和HashSet的区别是:-

HashMap contains key value pairs and each value can be accessed by key where as HashSet needs to be iterated everytime as there is no get method. HashMap implements Map interface and allows one null value as a key and multiple null values as values, whereas HashSet implements Set interface, allows only one null value and no duplicated values.(Remeber one null key is allowed in HashMap key hence one null value in HashSet as HashSet implemements HashMap internally). HashSet and HashMap do not maintain the order of insertion while iterating.