Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java StringBuilder have a constructor for CharSequence and another one for String?

Knowing that String implements CharSequence interface, so why does StringBuilder have a constructor for CharSequence and another one for String? No indication in the javadoc !

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {...}
public final class StringBuilder
    extends AbstractStringBuilder
    implements java.io.Serializable, CharSequence
{

...

    /**
     * Constructs a string builder initialized to the contents of the
     * specified string. The initial capacity of the string builder is
     * {@code 16} plus the length of the string argument.
     *
     * @param   str   the initial contents of the buffer.
     */
    public StringBuilder(String str) {
        super(str.length() + 16);
        append(str);
    }

    /**
     * Constructs a string builder that contains the same characters
     * as the specified {@code CharSequence}. The initial capacity of
     * the string builder is {@code 16} plus the length of the
     * {@code CharSequence} argument.
     *
     * @param      seq   the sequence to copy.
     */
    public StringBuilder(CharSequence seq) {
        this(seq.length() + 16);
        append(seq);
    }
...
}
like image 584
AbdelRahmane Avatar asked May 13 '19 06:05

AbdelRahmane


People also ask

What is the difference between CharSequence and string?

A CharSequence is an Interface. String is an immutable sequence of characters and implements the CharSequence interface. CharSequence[] and String[] are just arrays of CharSequence and String respectively.

What will the StringBuilder constructor do?

Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.

Why did you use StringBuilder instead of string?

StringBuilder is used to represent a mutable string of characters. Mutable means the string which can be changed. So String objects are immutable but StringBuilder is the mutable string type.

What is the difference between string and StringBuilder in Java?

String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer. String concatenation operator (+) internally uses StringBuffer or StringBuilder class.


Video Answer


1 Answers

Optimization. If I am not mistaken, there are two implementations of append. append(String) is more efficient than append(CharSequence) where CharSequence is a string. If I had to do some extra routine to check to make sure the CharSequence is compatible with String, convert it to String, and run the append(String), that would be longer than append(String) directly. Same result. Different speed.

like image 72
George Xavier Avatar answered Oct 16 '22 09:10

George Xavier