Reputation: 390
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) ?
Upvotes: 4
Views: 254
Reputation: 121702
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.
Upvotes: 4
Reputation: 2985
public StringBuffer(String str) : Constructs a string buffer initialized to the contents of the specified string. The initial capacity of the string buffer is 16 plus the length of the string argument.
public StringBuffer(CharSequence seq) : Constructs a string buffer that contains the same characters as the specified CharSequence. The initial capacity of the string buffer is 16 plus the length of the CharSequence argument. If the length of the specified CharSequence is less than or equal to zero, then an empty buffer of capacity 16 is returned.
Upvotes: 0
Reputation: 201409
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
Upvotes: 5