除了HashSet不允许重复值之外,HashMap和HashSet之间还有什么区别呢?
我是说执行方面?这有点模糊,因为两者都使用哈希表来存储值。
除了HashSet不允许重复值之外,HashMap和HashSet之间还有什么区别呢?
我是说执行方面?这有点模糊,因为两者都使用哈希表来存储值。
当前回答
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.
其他回答
HashMap是一个Map实现,允许重复的值,但不允许重复的键。添加对象需要一个键/值对。允许使用空键和空值。例如:
{,世界- > 5 - > 3 - > 2,好- > 4}
HashSet是一个Set实现,它不允许重复。如果您试图添加一个重复的对象,调用公共布尔add(object o)方法,则该集合保持不变并返回false。例如:
(,世界,好)
HashSet在内部使用HashMap来存储它的条目。内部HashMap中的每个条目都由一个Object进行键控,因此所有条目都散列到同一个bucket中。我不记得内部HashMap使用什么来存储它的值,但这并不重要,因为内部容器永远不会包含重复的值。
编辑:针对马修的评论,他是对的;我想反了。内部HashMap由组成Set元素的对象作为键。HashMap的值是一个简单地存储在HashMap桶中的对象。
hashmap允许一个空键和空值。它们不是同步的,这提高了效率。如果需要,您可以使用Collections.SynchronizedMap()使它们同步。
哈希表不允许空键,并且是同步的。
真可惜他们的名字都是以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
更多信息请参考这篇文章。