String is one of the most used classes in any programming language. We know that String is immutable and final in java and java runtime maintains a String pool that makes it a special class.
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.
Note : HashMap uses hashCode() and equals() methods on keys for get and put operations. So HashMap key object should provide good implementation of these methods. This is the reason immutable classes are better suitable for keys,
Let's say, We have some data of the students and we need to keep that data for further processing in a Hashmap.
HashMap<String, String> students = new HashMap<>();
students.put("S1", "Student1");
students.put("S2", "Student2");
students.put("S3", "Student3");
students.put("S4", "Student4");
students.put("S5", "Student5");
students.put("S6", "Student6");
Here we have used some Strings as key in Hashmap. Now we have put 6 students data into the students map and due to immutability of the String all the keyswill be catched into the system and while retrieving the value of the object based on key system no need to calculate the hashcode of the key again and again. So with little efforts we can get the value against the key.
String s1 = students.get("S1");
Comments
Post a Comment