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

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


当前回答

基本上在HashMap中,用户必须同时提供Key和Value,而在HashSet中只提供Value, Key是通过哈希函数从Value自动派生出来的。因此,在拥有Key和Value之后,HashSet可以在内部存储为HashMap。

其他回答

顾名思义,HashMap是一个关联Map(从键映射到值),HashSet只是一个Set。

差异: 关于等级制度: HashSet实现Set。 HashMap实现Map并存储键和值的映射。

在数据库中使用HashSet和HashMap将帮助您理解它们的重要性。 HashSet:通常用于存储唯一的集合对象。 例如:它可以用作存储之间的多对一关系的实现类 class Item和class Bid where (Item有多个投标) HashMap:用于将键映射到值。该值可以为null或Object的任意Object /list (Object本身就是Object)。

编辑-这个答案不正确。我把它放在这里,以防其他人有类似的想法。B.roth和justkt的答案正确。

——原创——

您基本上回答了自己的问题——hashset不允许重复值。使用支持哈希映射构建哈希集是很简单的(只是检查一下该值是否已经存在)。我想各种Java实现要么做到这一点,要么实现一些自定义代码来更有效地做到这一点。

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

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.

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.