除了HashSet不允许重复值之外,HashMap和HashSet之间还有什么区别呢?
我是说执行方面?这有点模糊,因为两者都使用哈希表来存储值。
除了HashSet不允许重复值之外,HashMap和HashSet之间还有什么区别呢?
我是说执行方面?这有点模糊,因为两者都使用哈希表来存储值。
当前回答
Java中HashSet和HashMap的区别
1) HashMap和HashSet之间的第一个也是最重要的区别是HashMap是Map接口的实现,而HashSet是Set接口的实现,这意味着HashMap是一个基于键值的数据结构,HashSet通过不允许重复来保证唯一性。在现实中,HashSet是Java中HashMap的包装器,如果你看一下HashSet. Java的add(E E)方法的代码,你会看到以下代码:
public boolean add(E e)
{
return map.put(e, PRESENT)==null;
}
其中,它将Object放入map中作为键和值,是一个最终对象PRESENT,它是dummy。
2) HashMap和HashSet的第二个区别是,我们使用add()方法将元素放入Set,但我们使用put()方法在Java中将键和值插入HashMap。
3) HashSet只允许一个空键,而HashMap可以允许一个空键+多个空值。
以上就是Java中HashSet和HashMap的区别。总之,HashSet和HashMap是两种不同类型的集合,一个是Set,另一个是Map。
其他回答
顾名思义,HashMap是一个关联Map(从键映射到值),HashSet只是一个Set。
HashSet和HashMap都是存储对,区别在于在HashMap中你可以指定一个键,而在HashSet中键来自对象的哈希代码
它们是完全不同的结构。HashMap是Map的实现。Map将键映射到值。键查找使用散列进行。
另一方面,HashSet是Set的实现。集合是用来匹配集合的数学模型的。正如您所注意到的,HashSet确实使用HashMap来支持其实现。但是,它实现了一个完全不同的接口。
当您正在寻找适合您的目的的最佳收藏时,本教程是一个很好的起点。如果你真的想知道发生了什么,也有一本书可以帮你。
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
更多信息请参考这篇文章。
HashSet在内部使用HashMap来存储它的条目。内部HashMap中的每个条目都由一个Object进行键控,因此所有条目都散列到同一个bucket中。我不记得内部HashMap使用什么来存储它的值,但这并不重要,因为内部容器永远不会包含重复的值。
编辑:针对马修的评论,他是对的;我想反了。内部HashMap由组成Set元素的对象作为键。HashMap的值是一个简单地存储在HashMap桶中的对象。