Tags

, , ,

Why hashcode() is not overridden for them? It is because, hashcode is used by the data structures that uses hashing algorithm to store the objects. Examples are: HashMap, HashTable, ConcurrentHashMap, HashSet  etc . Mostly such objects are used as key which are not meant to be changed throughout the program also called as immutable objects. Since StringBuilder/StringBuffer are expected to be mutated so, they are poor choices for such kind of roles.

Why equals () is not overridden for them? Well going by equals and hashCode contract in Java. If two objects are equal by equals method then there hashcode must be same. Now, had the equals method for StringBuilder/StringBuffer overridden, there corresponding hashcode method would also need to be overridden to follow that rule. But as explained earlier, these classes don’t need to have their own hashcode implementation and hence same is with their equals method.

StringBuilder/StringBuffer : 

1. StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized (which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized (which implies it isn’t thread safe).

2. The intended use of StringBuffer and StringBuilder is for maintaining a buffer of characters which may change with time.Their primary use is for constructing strings.

3. It is recommended to use StringBuilder over StringBuffer whenever possible because it is faster than StringBuffer. However if thread safety is necessary the best option is StringBuffer objects.

4.StringBuilder class is relatively new and was introduced in Java 1.5 whereas String and StringBuffer are old classes. StringBuffer and String class was introduced in JDK 1.0.

5.String is immutable while StringBuffer and StringBuilder is mutable object.

6.Use String if you require immutability, use Stringbuffer in java if you need mutable + Thread Safety and use StringBuilder in Java if you require mutable + without thread-safety.