StringBuffer类
背景:
1:String类是在所有项目中一定会使用到的一个功能类;
(1):每一个字符串的常量都属于一个String类的匿名对象;
(2):String有两个常量池:静态常量池,运行时常量池;
(3):String类对象实例化建议使用赋值的形式完成,这样可以直接将对象保存在对象池中以供下次重用。
2:StringBuffer类
3观察String和StringBuffer的对比
public class Test {
public static void main(String[] args) {
String str = "Hello " ;
change(str) ;
System.out.println(str);
}
public static void change(String temp) {
temp += "World !" ; // 内容并没有发生改变
}
}
//输出结果是hello
public class JavaAPIDemo {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer("Hello ") ;
change(buf) ;
System.out.println(buf.toString());
}
public static void change(StringBuffer temp) {
temp.append("World !") ; // 内容并没有发生改变
}
}
public class Test {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer("Hello ") ;
change(buf) ;
System.out.println(buf.toString());
}
public static void change(StringBuffer temp) {
temp.append("World !") ; // 内容发生改变
}
}
//输出结果
Hello World !
3:分析一下已有的问题
public class Test {
public static void main(String[] args) {
String strA = "www.mldn.cn" ;
String strB = "www." + "mldn" + ".cn" ;
System.out.println(strA == strB);
}
}
//输出结果:
//true
上述代码中,strB的对象内容不算是改变,对于现在的strB当程序编译之后会变为如下的形式,
StringBuffer buf = new StringBuffer();
buf.append(“www.”).append(“mldn”).append(“cn”);
所有的+在编译之后变成了StringBuffer中的append()方法,
4:StringBuffer与String类对象之间本来就可以直接互相转换:
String类对象变为StringBuffer可以依靠StringBuffer类的构造方法或利用append()方法;
所有类对象都可以通过toString()方法将其变为String类型。
5:StringBuffer类中的一些方法
public class Test {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer() ;
buf.append(".cn").insert(0, "www.").insert(4, "mldn") ;
System.out.println(buf);
}
}
//www.mldn.cn
public class Test {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer() ;
buf.append("Hello World !").delete(6, 12).insert(6, "MLDN") ;
System.out.println(buf);
}
}
//Hello MLDN!
public class Test {
public static void main(String[] args) {
StringBuffer buf = new StringBuffer() ;
buf.append("Hello World !") ;
System.out.println(buf.reverse());
}
}
//! dlroW olleH
6:StringBuilder