在我的java代码中我使用
StringBuffer sb = new StringBuffer();
String str = "";
sb.append(str + "abc"); //??
sb.insert(0,(str + "abc")); //??
任何人都可以告诉我这个 sb.append(str + "abc");
和 sb.insert(0,(str + "abc"));
最佳答案
在您的代码中,如 String str = "";
您看不到差异,但确实存在差异。
- 第一个附加在末尾。
- 在开头插入第二个。
看看这段代码:
1 附加:
String str = "abc";
StringBuilder sb = new StringBuilder("123");
sb.append("abc"); // str = "123abc"
// ↑ abc is appended at the end of sb
来自 API:
Appends the string representation of the char array argument to this sequence.
2插入:
String str = "abc";
StringBuilder sb0 = new StringBuilder("123");
sb.insert(0, str); // str = "abc123"
// ↑ abc is inserted at position 0 of sb0
StringBuilder sb1 = new StringBuilder("123");
sb.insert(1, str); // str = "1abc23"
// ↑ abc is inserted at position 1 of sb1
StringBuilder sb3 = new StringBuilder("123");
sb.insert(2, str); // str = "12abc3"
// ↑ abc is inserted at position 2 of sb2
StringBuilder sb4 = new StringBuilder("123");
sb.insert(3, str); // str = "123abc"
// ↑ abc is inserted at position 3 of sb2
所以...我们可以推断:StringBuilder.append == StringBuilder.insert(length)
insert(int offset, String str)
Inserts the string representation of the char array argument into this sequence. The characters of the array argument are inserted into the contents of this sequence at the position indicated by offset. The length of this sequence increases by the length of the argument.
关于java - StringBuffer追加和插入有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33170276/