Dafference between HashSet and HashMap - TongtongLan/Java GitHub Wiki
HashSet vs HashMap是一个经典的Java Collection面试问题,主要关注HashSet和HashMap在功能,用法和性能方面的区别。尽管它们都是基于散列的集合,但是底层接口是不同的。 HashSet通过扩展AbstractSetclass实现Set接口,HashMap实现Map接口。
Similarities on HashMap and HashSet in Java
-
都基于Collection接口
-
非线程同步的,无法在多个线程共享
-
迭代器都是 fail-fast 的
Iterator returned by HashMap's keySet() and HashSet are fail-fast and they throw ConcurrentModificationException if they detect any structural change in Collection.
- 一些基本操作的性能是常数时间的
Both HashMap and HashSet provided constant time performance for basic operations like put(), get() etc.
- 都允许插入空值
HashMap permits null values and the null key.and HashSet permits the null element.
Differences between HashSet and HashMap in Java
- 实现的底层接口不同,一个是Set接口,一个是Map接口
The first and most significant difference between HashMap and HashSet is that HashMap is an implementation of Map interface while HashSet is an implementation of Set interface, which means HashMap is a key value based data-structure and HashSet guarantees uniqueness by not allowing duplicates.In reality, HashSet is a wrapper around HashMap in Java, if you look at the code of add(E e) method of HashSet.
java you will see following code :
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
where it's putting Object into a map as key and value is a final object PRESENT which is a dummy.
private static final Object PRESENT = new Object();
- 插入值的方法不同
The second difference between HashMap and HashSet is that we use add() method to put elements into Set but we use put() method to insert key and value into HashMap in Java.
- HashSet allows only one null key, but HashMap can allow one null key + multiple null values.
Read more: http://www.java67.com/2012/08/difference-between-hashset-and-hashmap.html#ixzz51883pdte