Why is HashMap faster than HashSet?

怎甘沉沦 提交于 2019-12-02 19:33:57

Performance:

If you look at the source code of HashSet (at least JDK 6, 7 and 8), it uses HashMap internally, so it basically does exactly what you are doing with sample code.

So, if you need a Set implementation, you use HashSet, if you need a Map - HashMap. Code using HashMap instead of HashSet will have exactly the same performance as using HashSet directly.

Choosing the right collection

Map - maps keys to values (associative array) - http://en.wikipedia.org/wiki/Associative_array.

Set - a collection that contains no duplicate elements - http://en.wikipedia.org/wiki/Set_(computer_science).

If the only thing you need your collection for is to check if an element is present in there - use Set. Your code will be cleaner and more understandable to others.

If you need to store some data for your elements - use Map.

None of these answers really explain why HashMap is faster than HashSet. They both have to calculate the hashcode, but think about the nature of the key of a HashMap - it is typically a simple String or even a number. Calculating the hashcode of that is much faster than the default hashcode calculation of an entire object. If the key of the HashMap was the same object as that stored in a HashSet, there would be no real difference in performance. The difference comes in the what sort of object is the HashMap's key.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!