Example & Tutorial understanding programming in easy ways.

Why String is popular HashMap key in Java?

As we discuss above String is immutable, its hashcode is cached at the time of creation and it doesnít need to be calculated again. This makes it a great candidate for key in a Map and itís processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.Keyís hash code is used primarily in conjunction to its equals() method, for putting a key in map and then getting it back from map. So, our only focus point is these two methods. So if hash code of key object changes after we have put a key value pair in map, then its almost impossible to fetch the value object back from map. It is a case of memory leak.

On runtime, JVM computes hash code for each object and provide it on demand. When we modify an objectís state, JVM set a flag that object is modified and hash code must be AGAIN computed. So, next time you call objectís hashCode() method, JVM recalculate the hash code for that object.

For this basic reasoning, key objects are suggested to be IMMUTABLE. IMMUTABILITY allows you to get same hash code every time, for a key object. So it actually solves most of the problems in one go. Also, this class must honor the hashCode() and equals() methods contract.

example:

import java.util.HashMap;

public class stringhashtest {

public static void main(String[] args) {

// Create new HashMap.

// ... Uses diamond inference on right side.

HashMap<String, Integer> hash = new HashMap<>();

// Put three keys with values.

hash.put("banana", 1);

hash.put("orange", 2);

hash.put("mango", 3);

// Look up some known values.

int a = hash.get("banana");

int b = hash.get("orange");

// Display results.

System.out.println(a);

System.out.println(b);}}










  

Read More →