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

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


当前回答

HashMap是Map接口的实现 HashSet是Set Interface的一个实现

以键值对的形式存储数据 HashSet只存储对象

Put方法用于在map中添加元素 Add方法用于将元素添加为Set

在哈希映射中,哈希码值使用键对象计算 这里成员对象用于计算hashcode值,这可以是相同的两个对象,因此equal()方法用于检查是否相等,如果返回false,这意味着两个对象是不同的。

HashMap比hashset快,因为使用唯一键访问对象 HashSet比Hashmap慢

其他回答

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

——原创——

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

HashMap是Map接口的实现 HashSet是Set Interface的一个实现

以键值对的形式存储数据 HashSet只存储对象

Put方法用于在map中添加元素 Add方法用于将元素添加为Set

在哈希映射中,哈希码值使用键对象计算 这里成员对象用于计算hashcode值,这可以是相同的两个对象,因此equal()方法用于检查是否相等,如果返回false,这意味着两个对象是不同的。

HashMap比hashset快,因为使用唯一键访问对象 HashSet比Hashmap慢

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

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

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

HashSet

HashSet class implements the Set interface In HashSet, we store objects(elements or values) e.g. If we have a HashSet of string elements then it could depict a set of HashSet elements: {“Hello”, “Hi”, “Bye”, “Run”} HashSet does not allow duplicate elements that mean you can not store duplicate values in HashSet. HashSet permits to have a single null value. HashSet is not synchronized which means they are not suitable for thread-safe operations until unless synchronized explicitly.[similarity] add contains next notes HashSet O(1) O(1) O(h/n) h is the table

HashMap

HashMap class implements the Map interface HashMap is used for storing key & value pairs. In short, it maintains the mapping of key & value (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This is how you could represent HashMap elements if it has integer key and value of String type: e.g. {1->”Hello”, 2->”Hi”, 3->”Bye”, 4->”Run”} HashMap does not allow duplicate keys however it allows having duplicate values. HashMap permits single null key and any number of null values. HashMap is not synchronized which means they are not suitable for thread-safe operations until unless synchronized explicitly.[similarity] get containsKey next Notes HashMap O(1) O(1) O(h/n) h is the table

更多信息请参考这篇文章。