Just to add my experience working with StringBuilder:
StringBuilder hasn't got an overridden equals() method, so if you want to see whether two StringBuilders have the same contents try
builder1.toString().equals(builder2.toString()).
For example:
StringBuilder a = new StringBuilder("rupali");
StringBuilder b = new StringBuilder("rupali");
If we want to check if content of a and b are same (as we do in StringBuffer or String class with equals() method)
if (a.equals(b))
{ System.out.println("Equal"); }
else {System.our.println("Not equal"); }
Unlike String or StringBuffer, this will give "Not equal" as answer.
The correct implementation to check equals() in case of StringBuilder is:
if (a.toString().equals(b.toString()))
{ System.out.println("Equal"); }
else {System.our.println("Not equal"); }
The answer is "Equal".
Criteria to choose among String, StringBuffer and StringBuilder
1. If your text is not going to change use a string Class because a String object is immutable.
2. If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
3. If your text can change, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.
Thanks
Rupali
StringBuilder hasn't got an overridden equals() method, so if you want to see whether two StringBuilders have the same contents try
builder1.toString().equals(builder2.toString()).
For example:
StringBuilder a = new StringBuilder("rupali");
StringBuilder b = new StringBuilder("rupali");
If we want to check if content of a and b are same (as we do in StringBuffer or String class with equals() method)
if (a.equals(b))
{ System.out.println("Equal"); }
else {System.our.println("Not equal"); }
Unlike String or StringBuffer, this will give "Not equal" as answer.
The correct implementation to check equals() in case of StringBuilder is:
if (a.toString().equals(b.toString()))
{ System.out.println("Equal"); }
else {System.our.println("Not equal"); }
The answer is "Equal".
Criteria to choose among String, StringBuffer and StringBuilder
1. If your text is not going to change use a string Class because a String object is immutable.
2. If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
3. If your text can change, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.
Thanks
Rupali
No comments:
Post a Comment