Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

java - How StringBuffer behaves When Passing Char as argument to its Overloaded Constructor?

    StringBuffer sb = new StringBuffer('A');
    System.out.println("sb = " + sb.toString());
    sb.append("Hello");
    System.out.println("sb = " + sb.toString());

Output:

sb =

sb = Hello

But if i pass a String instead of character, it appends to Hello . Why is this strange behavior with char ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no constructor which accepts a char. You end up with the int constructor due to Java automatically converting your char to an int, thus specifying the initial capacity.

/**
 * Constructs a string buffer with no characters in it and
 * the specified initial capacity.
 *
 * @param      capacity  the initial capacity.
 * @exception  NegativeArraySizeException  if the <code>capacity</code>
 *               argument is less than <code>0</code>.
 */
public StringBuffer(int capacity) {
    super(capacity);
}

Cf. this minimal example:

public class StringBufferTest {
    public static void main(String[] args) {
        StringBuffer buf = new StringBuffer('a');
        System.out.println(buf.capacity());
        System.out.println((int) 'a');
        StringBuffer buf2 = new StringBuffer('b');
        System.out.println(buf2.capacity());
        System.out.println((int) 'b');
    }
}

Output:

97
97
98
98

Whereas

StringBuffer buf3 = new StringBuffer("a");
System.out.println(buf3.capacity());

Results in an initial capacity of 17.

You might have confused char with CharSequence (for which there is indeed a constructor), but these are two completely different things.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...