除了HashSet不允许重复值之外,HashMap和HashSet之间还有什么区别呢?
我是说执行方面?这有点模糊,因为两者都使用哈希表来存储值。
除了HashSet不允许重复值之外,HashMap和HashSet之间还有什么区别呢?
我是说执行方面?这有点模糊,因为两者都使用哈希表来存储值。
当前回答
它们之间的主要区别如下:
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
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中,用户必须同时提供Key和Value,而在HashSet中只提供Value, Key是通过哈希函数从Value自动派生出来的。因此,在拥有Key和Value之后,HashSet可以在内部存储为HashMap。
Java中HashSet和HashMap的区别
HashSet内部使用HashMap存储对象。当add(String)方法调用时,它调用HahsMap put(key,value)方法,其中key=字符串对象& value=新对象(Dummy)。所以它不维护重复,因为键只是值对象。
在Hashset/HashMap中作为key存储的对象应该覆盖hashcode & equals契约。
用于访问/存储HashMap中的值对象的键应该声明为Final,因为当它被修改时,value对象不能被定位并返回null。
HashSet和HashMap都是存储对,区别在于在HashMap中你可以指定一个键,而在HashSet中键来自对象的哈希代码
编辑-这个答案不正确。我把它放在这里,以防其他人有类似的想法。B.roth和justkt的答案正确。
——原创——
您基本上回答了自己的问题——hashset不允许重复值。使用支持哈希映射构建哈希集是很简单的(只是检查一下该值是否已经存在)。我想各种Java实现要么做到这一点,要么实现一些自定义代码来更有效地做到这一点。