Why StringBuffer/StringBuilder should be avoided in HashMap?

Why StringBuffer/StringBuilder should be avoided in HashMap?

 

This is one of the core java interview question under collections category. Generally in all the map manipulations we use string and avoid stringbuffer and stringbuilders, because both are mutable.

What is the issue if is mutable ?
If you are keeping your hashmap’s key/value as stringbuilder/stringbuffer then once after you inserted the value in the map, if any of the key/value modified then it actually affects inside the map as well, even if you won’t perform the put operation with the modified value.

Because stringbuffer/stringbuilder is mutable, it is actually modifying or changing the value in all the places, so it involves high risk to use these as key/values in any collections.

 

 

HashMap with Mutable (StringBuffer/StringBuilder):

  • Here StringBuffer is map key and StringBuilder is map value.
  • I have added the key as java and value as oracle.
  • Now I modified the same key and value.
  • But without performing any additional put/map operations it got changed inside the map as well.
  • To avoid data inconsistency issue, we should avoid stringbuffer/stringbuilder in map.

[java]
package in.javadomain;
import java.util.HashMap;

public class HashStringBuffer {

public static void main(String[] args) {

System.out.println(“StringBuffer-StringBuilder Key / Value Modify After Map Put:”);
StringBuffer myKey =new StringBuffer(“java”);
StringBuilder myValue = new StringBuilder(“oracle”);
HashMap myMap = new HashMap();
myMap.put(myKey, myValue);
System.out.println(“Before Modify => “+myMap);
myKey.append(“9”);
myValue.append(“.com”);
System.out.println(“After Modify => “+myMap);

}
}
[/java]

Output:
[plain]
StringBuffer-StringBuilder Key / Value Modify After Map Put:
Before Modify => {java=oracle}
After Modify => {java9=oracle.com}
[/plain]

 

 

HashMap with Immutable (String):

Eventhough the string values modified, due to its immutable character it is not affecting the collection/map.

[java]
package in.javadomain;
import java.util.HashMap;
public class HashStringBuffer {
public static void main(String[] args) {
System.out.println(“String Key / Value Modify After Map Put:”);
String myKeyString =new String(“java”);
String myValueString = new String(“oracle”);
HashMap myMapString = new HashMap();
myMapString.put(myKeyString, myValueString);
System.out.println(“Before Modify String => “+myMapString);
myKeyString.concat(“9”);
myValueString.concat(“.com”);
System.out.println(“After Modify String => “+myMapString);
}
}
[/java]

Output:
[plain]
String Key / Value Modify After Map Put:
Before Modify String => {java=oracle}
After Modify String => {java=oracle}
[/plain]

Hope it helps!

Leave a Reply