我一直在阅读/研究为什么 HashMap 快于 HashSet 。
我不完全理解以下语句:
HashMap 比 HashSet 快,因为这些值与唯一键相关联。
总结我的问题:
我认为 HashMap 和 HashSet 以相同的方式计算哈希码。为什么它们不同?
HashMap 可以做与 HashSet code>,并且更快。为什么我们需要 HashSet ?例子:
HashMap< Object1,Boolean> = new HashMap< Object1,boolean>(); map.put(obj1,true); =>存在 map.get(obj1); => if null = not exist,else exists
如果您查看HashSet的源代码(至少JDK 6 ,7和8),它在内部使用HashMap,所以它基本上完成了你对样例代码的处理。
所以,如果你需要一个Set实现,你可以使用HashSet,如果你需要一个Map - HashMap。使用HashMap代替HashSet的代码与使用HashSet的性能完全相同。选择正确的集合
映射 - 将键映射到值(关联数组) - http:// en .wikipedia / wiki / Associative_array 。
Set - 一个不包含重复元素的集合 - en.wikipedia/wiki/Set_(computer_science)。
如果您需要收集的唯一东西是检查一个元素是否存在 - 请使用Set。您的代码将更清晰,更易于理解。
如果您需要为元素存储一些数据,请使用Map。
I have been reading/researching the reason why HashMapis faster than HashSet.
I am not quite understanding the following statements:
HashMap is faster than HashSet because the values are associated to a unique key.
In HashSet, member object is used for calculating hashcode value which can be same for two objects so equals() method is used to check for equality. If it returns false, that means the two objects are different. In HashMap, the hashcode value is calculated using the key object.
The HashMap hashcode value is calculated using the key object. Here, the member object is used to calculate the hashcode, which can be the same for two objects, so equals() method is used to check for equality. If it returns false, that means the two objects are different.
To conclude my question:
I thought HashMap and HashSet calculate the hashcode in the same way. Why are they different?
Can you provide a concrete example how HashSet and HashMap calculating the hashcode differently?
I know what a "key object" is, but what does it mean by "member object"?
HashMap can do the same things as HashSet, and faster. Why do we need HashSet? Example:
HashMap <Object1, Boolean>= new HashMap<Object1, boolean>(); map.put("obj1",true); => exist map.get("obj1"); =>if null = not exist, else exist解决方案
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) - en.wikipedia/wiki/Associative_array.
Set - a collection that contains no duplicate elements - en.wikipedia/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.
更多推荐
为什么HashMap比HashSet更快?
发布评论