Java – why is HashMap faster than HashSet?
I've been reading / searching why HashMap is faster than HashSet
I am not familiar with the following statement
>HashMap is faster than HashSet because these values are associated with unique keys > in HashSet, member objects are used to calculate hash code values. For two objects that are the same, the equal () method is used to check whether they are equal. Returning false indicates that the two objects are different In HashMap, use key objects to calculate hash code values. > The hash mapping hash code value is calculated using the key object. Here, the member object is used to calculate the same hash code value. For two objects, the equal sign () method is used to check whether they are equal. Returning false indicates that the two objects are different
So let me end my question
>I think HashMap and HashSet calculate hash codes in the same way. Why are they different? > You can provide a specific example. How do hash sets and hash marks calculate hash codes differently? > I know what a key object is, but what does a member object mean? > HashMap can do something with 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
Solution
Performance:
If you look at the source code of HashSet (at least JDK 6), you use HashMap internally, so it basically conforms to what you do with the sample code
Therefore, if you need a set implementation, you can use HashSet. If you need a map – HashMap The code using HashMap instead of HashSet will have exactly the same performance as using HashSet directly
Select the correct set
Map – map keys to values (associative array) – http://en.wikipedia.org/wiki/Associative_array.
Set – a set that does not contain duplicate elements – http://en.wikipedia.org/wiki/Set_ (computer_science).
If the only thing you need is to check whether an element exists - use set Your code will be clearer and easier to understand
If you need to store some data for your elements – use maps