java - I don't understand the code on line 13. Are sb and str not the same type?
漂亮男人
漂亮男人 2017-05-17 10:04:19
0
2
350
public class TestStringBuffer{
    public static void main(String[] args){
        StringBuffer sb = new StringBuffer();
        sb.append("abc");
        sb.append("123");
        System.out.println("sb = " + sb); 
        sb.insert(3, "--"); 
        System.out.println("sb = " + sb); 
        sb.delete(2,6); 
        System.out.println("sb = " + sb);
        sb.reverse();
        System.out.println("sb = " + sb); 
        String str = sb.toString();  // 13行
        System.out.printf("str = " + str);
    }
}
漂亮男人
漂亮男人

reply all(2)
阿神
StringBuffer 
String

How can this be the same type?StringBuffer在做字符串连接 + 或者输出的时候
会隐式执行toString()转化为String

Line 13 is the displayed execution sb.toString()sb转换为 String

Peter_Zhu

StringBuffer: String buffer
String: String
When modifying a string, you need to use the StringBuffer and StringBuilder classes.
Different from the String class, objects of the StringBuffer and StringBuilder classes can be modified multiple times without generating new unused objects .

The StringBuilder class was proposed in Java 5. The biggest difference between it and StringBuffer is that the methods of StringBuilder are not thread-safe (cannot be accessed synchronously).

Since StringBuilder has a speed advantage compared to StringBuffer, it is recommended to use the StringBuilder class in most cases. However, in cases where the application requires thread safety, the StringBuffer class must be used.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!