Java回顾之StringBuffer

1.StringBuffer()概述

线程安全的可变字符序列。
String是不可变的字符序列;StringBuffer是可变的字符序列。

2.StringBuffer()类的构造方法

StringBuffer的构造方法
	public StringBuffer():无参构造
	public StringBuffer(int capacity):指定容量的字符串缓冲对象
	public StringBuffer(String str):指定字符串内容的字符串缓冲对象
StringBuffer的方法
	public int capacity():返回当前容量,理论值
	public int length():返回长度(字符数),实际值
例:
	StringBuffer sb=new StringBuffer();
    System.out.println(sb.length());
    System.out.println(sb.capacity());
    输出:0
    	 16

3.StringBuffer()的添加功能

	public StringBuffer append(String str):可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身
	public StringBuffer insert(int offset,String str):在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身
注意:StringBuffer是字符串缓冲区,当new的时候是在堆内存创建了一个对象,底层是一个长度为16的字符数组,当调用
添加的方法时,不会再重新创建对象,而是不断地向缓冲区添加字符。
例:
	StringBuffer sb=new StringBuffer();
    StringBuffer sb2=sb.append("hello");
    StringBuffer sb3=sb.append("world");
    System.out.println(sb3);
    输出:helloworld

4.StringBuffer的删除功能

	public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回本身
	public StringBuffer delete(int start,int enda):删除从指定位置开始到指定位置结束的内容,并返回本身

5.StringBuffer的替换和反转

	public StringBuffer replace(int start,int end,String str):将从start到end的字符内容替换为str
	public StringBuffer reverse():字符串反转

6.StringBuffer的截取功能

	public String substring(int start):从指定位置截取到末尾
	public String substring(int start,int end):从start截取到end,注意包括开始位置不包括结束位置
	注意:返回值的类型不再是StringBuffer类型
例:
	StringBuffer sb=new StringBuffer("helloworld");
    String sb2=sb.substring(1,6);
    System.out.println(sb2);
    输出:ellow

7.String和StringBuffer相互转换

String->StringBuffer
	方法一:StringBuffer()的构造方法
	方法二:通过append()的方法
StringBuffer->String
	方法一:toString()方法
	方法二:通过substring(0,length)方法

8.StringBuffer和StringBuild的区别

StringBuffer是jdk1.0版本的,是线程安全的,效率低
StringBuild是jdk版本的,是线程不安全的,效率高

String和StringBuffer、StringBuild的区别

String是不可变的字符序列
StringBuffer、StringBuild是可变的字符序列

参数传递问题:
String类虽然是引用数据类型,但是他作为参数传递时和基本数据类型一样
StringBUffer是引用数据类型,当做参数传递时改变其值

猜你喜欢

转载自blog.csdn.net/weixin_42856363/article/details/104359862