除了HashSet不允许重复值之外,HashMap和HashSet之间还有什么区别呢?
我是说执行方面?这有点模糊,因为两者都使用哈希表来存储值。
除了HashSet不允许重复值之外,HashMap和HashSet之间还有什么区别呢?
我是说执行方面?这有点模糊,因为两者都使用哈希表来存储值。
当前回答
Java中HashSet和HashMap的区别
HashSet内部使用HashMap存储对象。当add(String)方法调用时,它调用HahsMap put(key,value)方法,其中key=字符串对象& value=新对象(Dummy)。所以它不维护重复,因为键只是值对象。
在Hashset/HashMap中作为key存储的对象应该覆盖hashcode & equals契约。
用于访问/存储HashMap中的值对象的键应该声明为Final,因为当它被修改时,value对象不能被定位并返回null。
其他回答
HashSet是一个集合,例如{1,2,3,4,5}
HashMap是key ->值(键到值)映射,例如{a -> 1, b -> 2, c -> 2, d -> 1}
注意,在我上面的例子中,HashMap中不能有重复的键,但它可能有重复的值。
在HashSet中,必须没有重复的元素。
hashmap允许一个空键和空值。它们不是同步的,这提高了效率。如果需要,您可以使用Collections.SynchronizedMap()使它们同步。
哈希表不允许空键,并且是同步的。
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是Map接口的实现 HashSet是Set Interface的一个实现
以键值对的形式存储数据 HashSet只存储对象
Put方法用于在map中添加元素 Add方法用于将元素添加为Set
在哈希映射中,哈希码值使用键对象计算 这里成员对象用于计算hashcode值,这可以是相同的两个对象,因此equal()方法用于检查是否相等,如果返回false,这意味着两个对象是不同的。
HashMap比hashset快,因为使用唯一键访问对象 HashSet比Hashmap慢
HashSet是根据HashMap实现的。它是键和PRESENT对象之间的映射。