除了HashSet不允许重复值之外,HashMap和HashSet之间还有什么区别呢?
我是说执行方面?这有点模糊,因为两者都使用哈希表来存储值。
除了HashSet不允许重复值之外,HashMap和HashSet之间还有什么区别呢?
我是说执行方面?这有点模糊,因为两者都使用哈希表来存储值。
当前回答
它们是完全不同的结构。HashMap是Map的实现。Map将键映射到值。键查找使用散列进行。
另一方面,HashSet是Set的实现。集合是用来匹配集合的数学模型的。正如您所注意到的,HashSet确实使用HashMap来支持其实现。但是,它实现了一个完全不同的接口。
当您正在寻找适合您的目的的最佳收藏时,本教程是一个很好的起点。如果你真的想知道发生了什么,也有一本书可以帮你。
其他回答
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
更多信息请参考这篇文章。
hashmap允许一个空键和空值。它们不是同步的,这提高了效率。如果需要,您可以使用Collections.SynchronizedMap()使它们同步。
哈希表不允许空键,并且是同步的。
HashMap是用来添加、获取、删除…由任何类型的自定义键索引的对象。 HashSet用于添加元素,删除元素,并通过比较它们的哈希值来检查元素是否存在。
HashMap包含元素,HashSet记住它们的哈希值。
HashSet是一个集合,例如{1,2,3,4,5}
HashMap是key ->值(键到值)映射,例如{a -> 1, b -> 2, c -> 2, d -> 1}
注意,在我上面的例子中,HashMap中不能有重复的键,但它可能有重复的值。
在HashSet中,必须没有重复的元素。