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

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

StringBuffer(CharSequence chars) 

      

and

StringBuffer(String str)

      

2. What is the main difference between String and CharSequence (Custom Functionality)?

+3


source to share


3 answers


A CharSequence

is an interface; it happens that it String

implements it.

This means that, for example, when you call .charAt()

in String

, what is actually called the implementation String

for that method CharSequence

.

As you can see from the javadoc CharSequence

, not many classes in the JDK actually implement this interface.



As for the two constructors, this StringBuffer

is Java 1.0 and CharSequence

only appears in 1.4; however this also applies to StringBuilder

(which you should use instead of StringBuffer

) has two constructors (one with a CharSequence

as an argument, the other with String

c as an argument), so there is probably an optimization when a String

is passed as an argument. For such optimizations, this is the Use Source, Luke (tm) case.

As an example of an implementation CharSequence

that is missing from the JDK, you can, for example, see one of my projects: largetext . Note that, among other things, generating a Matcher

from Pattern

uses CharSequence

rather than String

as an argument
; and since it String

implements CharSequence

, well, passing String

as an argument.

+4


source


CharSequence

is an interface, so you cannot create it directly. String

is a concrete class that implements the interface CharSequence

. StringBuffer

also implements the interface CharSequence

.



As for why it StringBuffer

has two constructors, one that takes String

and one that takes CharSequence

, it's almost certainly because (per line Since

in the Javadoc) was CharSequence

n't added until Java v1.4 until StringBuffer

(and String

) were in Java 1.0

+5


source


public StringBuffer (String str): Creates a string buffer initialized with 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): Creates a string buffer containing 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, an empty buffer with a throughput of 16 is returned.

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/StringBuffer.java#StringBuffer.%3Cinit%3E%28java.lang.String%29

0


source







All Articles