Java类库之StringBuffer类(重点)

时间:2022-06-19
本文章向大家介绍Java类库之StringBuffer类(重点),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在讲解StringBuffer类之前首先来简单回顾一下String类的特点:

· String类的对象有两种实例化方式,一种是直接赋值,只会开辟一块堆内存空间,而且对象可以自动入池,另外一种方式使用构造方法完成,会开辟两块空间,有一块空间将成为垃圾,并且不会自动入池,但是可以通过intern()方法手工入池; · 字符串常量一旦声明则不可改变,而字符串对象可以改变,但是改变的是其内存地址的指向;

通过以上的几个特点就可以清楚的发现,String类是表示字符串使用最多的类,但是其不适合于被频繁修改的字符串操作上,所以在这种情况下,往往可以使用StringBuffer类,即:StringBuffer类方便用户进行内容的修改。在String类之中使用“+”作为数据库的连接操作,而在StringBuffer类之中使用append()方法进行数据的连接。

范例:使用StringBuffer操作,StringBuffer的内容可以改变

   public class TestDemo {
    	public static void main(String[] args) throws Exception {
    		StringBuffer buf = new StringBuffer();
    		buf.append("Hello ").append("World ."); // 连接内容
    		fun(buf);
    		System.out.println(buf);
    	}
    	public static void fun(StringBuffer temp) {
    		temp.append("n").append("Hello PKU");
    	}
    }

StringBuffer类在日后主要用于频繁修改字符串的操作上,但是在任何的开发之中,面对字符串的操作,98%都先考虑String,只有那2%会考虑StringBuffer。 现在表示字符串的操作类就有了两个:String、StringBuffer,那么下面通过这两个类的定义来研究一下关系:

现在发现String和StringBuffer类都实现了一个CharSequence接口,日后一定要记住,如果看见了CharSequence最简单的理解做法就是传字符串,但是虽然这两个类是同一个接口的子类,不过这两个类对象之间却不能互相直接转型。

操作一:将String变为StringBuffer · 方法一:直接利用StringBuffer类的构造方法,public StringBuffer(String str)

public class TestDemo {
	public static void main(String[] args) throws Exception {
		String str = "Hello World." ;
		StringBuffer buf = new StringBuffer(str);
		System.out.println(buf);
	}
}

· 方法二:利用StringBuffer类的append()方法

public class TestDemo {
	public static void main(String[] args) throws Exception {
		String str = "Hello World ." ;
		StringBuffer buf = new StringBuffer();
		buf.append(str) ;
		System.out.println(buf);	
   }
}

操作二:将StringBuffer变为String,利用StringBuffer类的toString()方法完成

public class TestDemo {
	public static void main(String[] args) throws Exception {
		StringBuffer buf = new StringBuffer();
		buf.append("Hello World .") ;
		String str = buf.toString() ;
		System.out.println(str); 
	}
}

在String类之中定义了许多的操作方法,同样,在StringBuffer类之中也定义了许多的操作方法,而且有些方法还是String类所有没有的支持。

范例:字符串反转操作,public StringBuffer reverse()

public class TestDemo {
	public static void main(String[] args) throws Exception {
		StringBuffer buf = new StringBuffer();
		buf.append("Hello World .") ;
		System.out.println(buf.reverse()); 
	}
}

范例:替换指定范围内的数据,public StringBuffer replace(int start, int end, String str)

public class TestDemo {
	public static void main(String[] args) throws Exception {
		StringBuffer buf = new StringBuffer();
		buf.append("Hello World .") ;
		System.out.println(buf.replace(6, 12, "PKU")); 
	}
}

范例:在指定位置上插入数据,public StringBuffer insert(int offset, 数据类型 变量)

public class TestDemo {
	public static void main(String[] args) throws Exception {
		StringBuffer buf = new StringBuffer();
		buf.append("World .").insert(0, "Hello ") ;
		System.out.println(buf); 
	}
}

面试题:请解释String和StringBuffer的区别?

String的内容不可改变,而StringBuffer的内容可以改变。