How is StringBuffer implementing append function without creating two objects?

后端 未结 10 1116
执念已碎
执念已碎 2021-01-30 09:22

It was an interview question. I was asked to implement the StringBuffer append function. I saw the code after the interview. But I cannot understand how the operati

10条回答
  •  旧时难觅i
    2021-01-30 09:48

    This doesn't compile.

    String S= "orange";
    S.append("apple");
    

    if you do

    final String S= "orange";
    final S2 = S + "apple";
    

    This doesn't create any objects as it is optimised at compile time to two String literals.

    StringBuilder s = new StringBuilder("Orange");
    s.append("apple");
    

    This creates two objects StringBuilder and the char[] it wraps. If you use

    String s2 = s.toString();
    

    This creates two more objects.

    If you do

    String S= "orange";
    S2 = S + "apple";
    

    This is the same as

    String S2 = new StringBuilder("orange").append("apple").toString();
    

    which creates 2 + 2 = 4 objects.

提交回复
热议问题