Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between StringBuffer(String str) and StringBuffer(CharSequence chars)

Tags:

java

string

1.I am confused between these two,Do they have different functionality if so then How ?

StringBuffer(CharSequence chars) 

and

StringBuffer(String str)

2. What is basic Difference between String And CharSequence(Specially functionality) ?

like image 282
Abin Lakhanpal Avatar asked Jan 09 '23 08:01

Abin Lakhanpal


2 Answers

CharSequence is an interface, so you cannot directly instantiate it. String is a concrete class that implements the CharSequence interface. StringBuffer also implements the CharSequence interface.

As for why StringBuffer has two constructors one that takes a String and one that takes a CharSequence, it is almost certainly because (per the Since line in the Javadoc) CharSequence was not added until Java v1.4 while StringBuffer (and String) were in Java 1.0

like image 116
Elliott Frisch Avatar answered Jan 12 '23 05:01

Elliott Frisch


A CharSequence is an interface; it happens that String implements it.

This means that for instance, when you call .charAt() on a String, what is really called is the implementation of String for this method of CharSequence.

As you can see from the javadoc of CharSequence, not many classes in the JDK actually implement this interface.

As to why two constructors, StringBuffer dates back to Java 1.0 and CharSequence appears in 1.4 only; however, this is also the case that StringBuilder (which you should use, really, instead of StringBuffer) has two constructors (one with a CharSequence as an argument, another with a String as an argument), so there are probably optimizations implied when a String is passed as an argument. As to what such optimizations could be, well, it is a case of "Use The Source, Luke"(tm).

As an example of a CharSequence implementation which is not in the JDK, you can for example see one of my projects: largetext. Note that among other things, generating a Matcher from a Pattern uses a CharSequence and not a String as an argument; and since String implements CharSequence, well, passing a String as an argument works.

like image 32
fge Avatar answered Jan 12 '23 04:01

fge