What is the most efficient key type in a hash map?

When using a HashMap , how much does the size of the object matter for retrieving elements when it comes to speed? Let's say I use a loop to repeat the possible keys of a large hash map. What would be the most efficient key type that I could use?

I am currently using String for the key type of an object due to simplicity for my sake. During coding, this question appeared in my head and amazed my curiosity. I tried to find this question on the Internet, but could not find the answer I was looking for. Thanks!

+4
source share
5 answers

The hash map will ask for your key for hashCode() . If the time taken to create the hash code is unreasonable, then the insertion time and search time for such objects will be high. Take java.net.URL for example. The hashcode method performs a DNS lookup. Such objects would not make good keys for a hash map.

There is no universal answer to what is the best key, since there is no better key. The best key to use in your hash map is the one you need to search. Just make sure the hashCode() key is fast and uses the int space appropriately.

+3
source
  • The key hashCode() and equals() should be fast

  • hashCode() should be well distributed to minimize hash collisions

+3
source

The implementation of the equals and hashCode methods is important. See The following: What issues should be considered when overriding equals and hashCode values ​​in Java?

Since these functions are used in hash operations, their effectiveness takes effect when you work in your collection.

As a support, the point indicated in the link should be taken into account:

Make sure that the hashCode () of the key objects that you put in the collection never changes while the object is in the collection. a bulletproof way to ensure that your keys are immutable, which has other benefits.

+1
source

In your case, the speed of the hashCode element method and equals method equals . Using Integer is fine, since they do not require special calculations for the hash value. Strings are also approved because the hash value is stored internally, although they work slower with equals .

+1
source

Are you trying to get values ​​from a HashMap using the get method or iterating over it? Regarding the get method, all the people above have answered this.

If you iterate over a HashMap using the entrySet method, the type of keys in your HashMap does not matter. In addition, having an entrySet entry at each iteration, finding values ​​becomes useless. Also note that an entrySet is usually preferable to a value method and a keySet method, since they both use the entrySet iterator internally and return either a key or a record value.

0
source

All Articles