StringBuffer 的 append 方法用于将指定的数据追加到 StringBuffer 对象的末尾。这个方法非常有用,特别是在需要频繁修改字符串内容的场景中,因为 StringBuffer 是可变的,而 String 是不可变的。
StringBuffer sb = new StringBuffer();
sb.append("Hello");
sb.append(" ");
sb.append("World");
System.out.println(sb.toString()); // 输出: Hello World
append 方法可以接受多种类型的数据,包括字符串、字符、整数、浮点数等。
StringBuffer sb = new StringBuffer();
sb.append("The answer is: ");
sb.append(42);
sb.append(", and the pi is approximately: ");
sb.append(3.14159);
System.out.println(sb.toString()); // 输出: The answer is: 42, and the pi is approximately: 3.14159
StringBuffer sb = new StringBuffer();
char[] chars = {'a', 'b', 'c'};
sb.append(chars);
sb.append(" ");
String[] strings = {"Hello", "World"};
sb.append(strings);
System.out.println(sb.toString()); // 输出: abc Hello World
StringBuffer sb = new StringBuffer();
sb.append(true);
sb.append(null);
System.out.println(sb.toString()); // 输出: truenull
对于其他对象,append 方法会调用对象的 toString 方法来获取其字符串表示。
StringBuffer sb = new StringBuffer();
Object obj = new Object();
sb.append(obj);
System.out.println(sb.toString()); // 输出: java.lang.Object@<hashcode>
虽然 StringBuffer 是线程安全的,但在单线程环境中,使用 StringBuilder 会更高效,因为 StringBuilder 没有同步开销。
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
System.out.println(sb.toString()); // 输出: Hello World
StringBuffer 的 append 方法是一个非常强大的工具,可以方便地将各种类型的数据追加到字符串缓冲区中。在多线程环境中,使用 StringBuffer 可以确保线程安全;在单线程环境中,使用 StringBuilder 可以提高性能。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。