1.String和StringBuffer类不能直接转换。如果要想互相转换,可以采用如下原则:
(1) String变为StringBuffer: 利用StringBuffer的构造方法或append()方法
(2)StringBuffer变为String: 调用toString
2.String类和StringBuffer类都是"CharSequence"接口的子类。这个接口描述的是一系列的字符集。所以字符串是字符集的子类,如果以后看CharSequence,最简单的联想就是字符串。
//反转操作
public synchronized StringBuffer reverse()
//删除操作,左闭右开
public synchronized StringBuffer delete(int start, int end)
//插入操作
public synchronized StringBuffer insert(int offset, 各种数据类型 b)
//1.
StringBuffer sb = new StringBuffer("helloworld"); System.out.println(sb.delete(5, 10).insert(0, "你好"));
结果:
你好hello
//2.
StringBuffer sb = new StringBuffer();
sb.append("hello").append("word");
System.out.println(sb.reverse());
System.out.println(sb.reverse());
System.out.println(sb.delete(0,5));
System.out.println(sb.insert(3, "p"));
结果:
drowolleh
helloword
word
worpd
String、StringBuffer、StringBuilder的区别:
- String的内容不可修改,String类的不可变性,StringBuffer与StringBuilder的内容可以修改.
- StringBuffer采用同步处理,效率低,属于线程安全操作;而StringBuilder采用异步处理,效率高,属于线程不安全操作。大多数实现中,StringBuffer要更快一些
StringBuffer和数组的区别
二者都可以看作是一个容器,装其他的数据;但是StringBuffer的数据最终是一个字符串数据,而数组可以放置多种数据,但必须是同一种数据类型。
形式参数问题
基本类型:形式参数的改变不影响实际参数;String作为参数传递效果和基本类型作为参数传递是一样的
引用类型:形式参数的改变直接影响实际参数
public class StringBufferDemo {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
System.out.println(s1 + "---" + s2);// hello---world
change(s1, s2);
System.out.println(s1 + "---" + s2);// hello---world
StringBuffer sb1 = new StringBuffer("hello");
StringBuffer sb2 = new StringBuffer("world");
System.out.println(sb1 + "---" + sb2);// hello---world
change(sb1, sb2);
System.out.println(sb1 + "---" + sb2);// hello---worldworld
}
public static void change(StringBuffer sb1, StringBuffer sb2) {
sb1 = sb2;//在原main中是没有变的,还是hello,但是在这里就变了,是world
sb2.append(sb1);//在原main函数中是变的,显示为worldworld
}
public static void change(String s1, String s2) {
s1 = s2;
s2 = s1 + s2;
}
}