本章介绍StringBuffer以及它的API的详细使用方法。

转载请注明出处:http://www.cnblogs.com/skywang12345/p/string03.html

StringBuffer 简介

StringBuffer 是一个线程安全的可变的字符序列。它继承于AbstractStringBuilder,实现了CharSequence接口。
StringBuilder 也是继承于AbstractStringBuilder的子类;但是,StringBuilder和StringBuffer不同,前者是非线程安全的,后者是线程安全的。

StringBuffer 和 CharSequence之间的关系图如下:

StringBuffer 函数列表

StringBuffer()
StringBuffer(int capacity)
StringBuffer(String string)
StringBuffer(CharSequence cs) StringBuffer append(boolean b)
StringBuffer append(int i)
StringBuffer append(long l)
StringBuffer append(float f)
StringBuffer append(double d)
synchronized StringBuffer append(char ch)
synchronized StringBuffer append(char[] chars)
synchronized StringBuffer append(char[] chars, int start, int length)
synchronized StringBuffer append(Object obj)
synchronized StringBuffer append(String string)
synchronized StringBuffer append(StringBuffer sb)
synchronized StringBuffer append(CharSequence s)
synchronized StringBuffer append(CharSequence s, int start, int end)
StringBuffer appendCodePoint(int codePoint)
int capacity()
synchronized char charAt(int index)
synchronized int codePointAt(int index)
synchronized int codePointBefore(int index)
synchronized int codePointCount(int beginIndex, int endIndex)
synchronized StringBuffer delete(int start, int end)
synchronized StringBuffer deleteCharAt(int location)
synchronized void ensureCapacity(int min)
synchronized void getChars(int start, int end, char[] buffer, int idx)
synchronized int indexOf(String subString, int start)
int indexOf(String string)
StringBuffer insert(int index, boolean b)
StringBuffer insert(int index, int i)
StringBuffer insert(int index, long l)
StringBuffer insert(int index, float f)
StringBuffer insert(int index, double d)
synchronized StringBuffer insert(int index, char ch)
synchronized StringBuffer insert(int index, char[] chars)
synchronized StringBuffer insert(int index, char[] chars, int start, int length)
synchronized StringBuffer insert(int index, String string)
StringBuffer insert(int index, Object obj)
synchronized StringBuffer insert(int index, CharSequence s)
synchronized StringBuffer insert(int index, CharSequence s, int start, int end)
int lastIndexOf(String string)
synchronized int lastIndexOf(String subString, int start)
int length()
synchronized int offsetByCodePoints(int index, int codePointOffset)
synchronized StringBuffer replace(int start, int end, String string)
synchronized StringBuffer reverse()
synchronized void setCharAt(int index, char ch)
synchronized void setLength(int length)
synchronized CharSequence subSequence(int start, int end)
synchronized String substring(int start)
synchronized String substring(int start, int end)
synchronized String toString()
synchronized void trimToSize()

StringBuffer源码(基于jdk1.7.40)

 package java.lang;

 public final class StringBuffer
extends AbstractStringBuilder
implements java.io.Serializable, CharSequence
{ static final long serialVersionUID = 3388685877147921107L; public StringBuffer() {
super(16);
} public StringBuffer(int capacity) {
super(capacity);
} public StringBuffer(String str) {
super(str.length() + 16);
append(str);
} public StringBuffer(CharSequence seq) {
this(seq.length() + 16);
append(seq);
} public synchronized int length() {
return count;
} public synchronized int capacity() {
return value.length;
} public synchronized void ensureCapacity(int minimumCapacity) {
if (minimumCapacity > value.length) {
expandCapacity(minimumCapacity);
}
} public synchronized void trimToSize() {
super.trimToSize();
} public synchronized void setLength(int newLength) {
super.setLength(newLength);
} public synchronized char charAt(int index) {
if ((index < 0) || (index >= count))
throw new StringIndexOutOfBoundsException(index);
return value[index];
} public synchronized int codePointAt(int index) {
return super.codePointAt(index);
} public synchronized int codePointBefore(int index) {
return super.codePointBefore(index);
} public synchronized int codePointCount(int beginIndex, int endIndex) {
return super.codePointCount(beginIndex, endIndex);
} public synchronized int offsetByCodePoints(int index, int codePointOffset) {
return super.offsetByCodePoints(index, codePointOffset);
} public synchronized void getChars(int srcBegin, int srcEnd, char[] dst,
int dstBegin)
{
super.getChars(srcBegin, srcEnd, dst, dstBegin);
} public synchronized void setCharAt(int index, char ch) {
if ((index < 0) || (index >= count))
throw new StringIndexOutOfBoundsException(index);
value[index] = ch;
} public synchronized StringBuffer append(Object obj) {
super.append(String.valueOf(obj));
return this;
} public synchronized StringBuffer append(String str) {
super.append(str);
return this;
} public synchronized StringBuffer append(StringBuffer sb) {
super.append(sb);
return this;
} public StringBuffer append(CharSequence s) {
// Note, synchronization achieved via other invocations
if (s == null)
s = "null";
if (s instanceof String)
return this.append((String)s);
if (s instanceof StringBuffer)
return this.append((StringBuffer)s);
return this.append(s, 0, s.length());
} public synchronized StringBuffer append(CharSequence s, int start, int end)
{
super.append(s, start, end);
return this;
} public synchronized StringBuffer append(char[] str) {
super.append(str);
return this;
} public synchronized StringBuffer append(char[] str, int offset, int len) {
super.append(str, offset, len);
return this;
} public synchronized StringBuffer append(boolean b) {
super.append(b);
return this;
} public synchronized StringBuffer append(char c) {
super.append(c);
return this;
} public synchronized StringBuffer append(int i) {
super.append(i);
return this;
} public synchronized StringBuffer appendCodePoint(int codePoint) {
super.appendCodePoint(codePoint);
return this;
} public synchronized StringBuffer append(long lng) {
super.append(lng);
return this;
} public synchronized StringBuffer append(float f) {
super.append(f);
return this;
} public synchronized StringBuffer append(double d) {
super.append(d);
return this;
} public synchronized StringBuffer delete(int start, int end) {
super.delete(start, end);
return this;
} public synchronized StringBuffer deleteCharAt(int index) {
super.deleteCharAt(index);
return this;
} public synchronized StringBuffer replace(int start, int end, String str) {
super.replace(start, end, str);
return this;
} public synchronized String substring(int start) {
return substring(start, count);
} public synchronized CharSequence subSequence(int start, int end) {
return super.substring(start, end);
} public synchronized String substring(int start, int end) {
return super.substring(start, end);
} public synchronized StringBuffer insert(int index, char[] str, int offset,
int len)
{
super.insert(index, str, offset, len);
return this;
} public synchronized StringBuffer insert(int offset, Object obj) {
super.insert(offset, String.valueOf(obj));
return this;
} public synchronized StringBuffer insert(int offset, String str) {
super.insert(offset, str);
return this;
} public synchronized StringBuffer insert(int offset, char[] str) {
super.insert(offset, str);
return this;
} public StringBuffer insert(int dstOffset, CharSequence s) {
// Note, synchronization achieved via other invocations
if (s == null)
s = "null";
if (s instanceof String)
return this.insert(dstOffset, (String)s);
return this.insert(dstOffset, s, 0, s.length());
} public synchronized StringBuffer insert(int dstOffset, CharSequence s,
int start, int end)
{
super.insert(dstOffset, s, start, end);
return this;
} public StringBuffer insert(int offset, boolean b) {
return insert(offset, String.valueOf(b));
} public synchronized StringBuffer insert(int offset, char c) {
super.insert(offset, c);
return this;
} public StringBuffer insert(int offset, int i) {
return insert(offset, String.valueOf(i));
} public StringBuffer insert(int offset, long l) {
return insert(offset, String.valueOf(l));
} public StringBuffer insert(int offset, float f) {
return insert(offset, String.valueOf(f));
} public StringBuffer insert(int offset, double d) {
return insert(offset, String.valueOf(d));
} public int indexOf(String str) {
return indexOf(str, 0);
} public synchronized int indexOf(String str, int fromIndex) {
return String.indexOf(value, 0, count,
str.toCharArray(), 0, str.length(), fromIndex);
} public int lastIndexOf(String str) {
// Note, synchronization achieved via other invocations
return lastIndexOf(str, count);
} public synchronized int lastIndexOf(String str, int fromIndex) {
return String.lastIndexOf(value, 0, count,
str.toCharArray(), 0, str.length(), fromIndex);
} public synchronized StringBuffer reverse() {
super.reverse();
return this;
} public synchronized String toString() {
return new String(value, 0, count);
} private static final java.io.ObjectStreamField[] serialPersistentFields =
{
new java.io.ObjectStreamField("value", char[].class),
new java.io.ObjectStreamField("count", Integer.TYPE),
new java.io.ObjectStreamField("shared", Boolean.TYPE),
}; private synchronized void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
java.io.ObjectOutputStream.PutField fields = s.putFields();
fields.put("value", value);
fields.put("count", count);
fields.put("shared", false);
s.writeFields();
} private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
java.io.ObjectInputStream.GetField fields = s.readFields();
value = (char[])fields.get("value", null);
count = fields.get("count", 0);
}
}

StringBuffer 示例

源码如下(StringBufferTest.java):

 /**
* StringBuffer 演示程序
*
* @author skywang
*/
import java.util.HashMap; public class StringBufferTest { public static void main(String[] args) {
testInsertAPIs() ;
testAppendAPIs() ;
testReplaceAPIs() ;
testDeleteAPIs() ;
testIndexAPIs() ;
testOtherAPIs() ;
} /**
* StringBuffer 的其它API示例
*/
private static void testOtherAPIs() { System.out.println("-------------------------------- testOtherAPIs --------------------------------"); StringBuffer sbuilder = new StringBuffer("0123456789"); int cap = sbuilder.capacity();
System.out.printf("cap=%d\n", cap); char c = sbuilder.charAt(6);
System.out.printf("c=%c\n", c); char[] carr = new char[4];
sbuilder.getChars(3, 7, carr, 0);
for (int i=0; i<carr.length; i++)
System.out.printf("carr[%d]=%c ", i, carr[i]);
System.out.println(); System.out.println();
} /**
* StringBuffer 中index相关API演示
*/
private static void testIndexAPIs() {
System.out.println("-------------------------------- testIndexAPIs --------------------------------"); StringBuffer sbuilder = new StringBuffer("abcAbcABCabCaBcAbCaBCabc");
System.out.printf("sbuilder=%s\n", sbuilder); // 1. 从前往后,找出"bc"第一次出现的位置
System.out.printf("%-30s = %d\n", "sbuilder.indexOf(\"bc\")", sbuilder.indexOf("bc")); // 2. 从位置5开始,从前往后,找出"bc"第一次出现的位置
System.out.printf("%-30s = %d\n", "sbuilder.indexOf(\"bc\", 5)", sbuilder.indexOf("bc", 5)); // 3. 从后往前,找出"bc"第一次出现的位置
System.out.printf("%-30s = %d\n", "sbuilder.lastIndexOf(\"bc\")", sbuilder.lastIndexOf("bc")); // 4. 从位置4开始,从后往前,找出"bc"第一次出现的位置
System.out.printf("%-30s = %d\n", "sbuilder.lastIndexOf(\"bc\", 4)", sbuilder.lastIndexOf("bc", 4)); System.out.println();
} /**
* StringBuffer 的replace()示例
*/
private static void testReplaceAPIs() { System.out.println("-------------------------------- testReplaceAPIs ------------------------------"); StringBuffer sbuilder; sbuilder = new StringBuffer("0123456789");
sbuilder.replace(0, 3, "ABCDE");
System.out.printf("sbuilder=%s\n", sbuilder); sbuilder = new StringBuffer("0123456789");
sbuilder.reverse();
System.out.printf("sbuilder=%s\n", sbuilder); sbuilder = new StringBuffer("0123456789");
sbuilder.setCharAt(0, 'M');
System.out.printf("sbuilder=%s\n", sbuilder); System.out.println();
} /**
* StringBuffer 的delete()示例
*/
private static void testDeleteAPIs() { System.out.println("-------------------------------- testDeleteAPIs -------------------------------"); StringBuffer sbuilder = new StringBuffer("0123456789"); // 删除位置0的字符,剩余字符是“123456789”。
sbuilder.deleteCharAt(0);
// 删除位置3(包括)到位置6(不包括)之间的字符,剩余字符是“123789”。
sbuilder.delete(3,6); // 获取sb中从位置1开始的字符串
String str1 = sbuilder.substring(1);
// 获取sb中从位置3(包括)到位置5(不包括)之间的字符串
String str2 = sbuilder.substring(3, 5);
// 获取sb中从位置3(包括)到位置5(不包括)之间的字符串,获取的对象是CharSequence对象,此处转型为String
String str3 = (String)sbuilder.subSequence(3, 5); System.out.printf("sbuilder=%s\nstr1=%s\nstr2=%s\nstr3=%s\n",
sbuilder, str1, str2, str3); System.out.println();
} /**
* StringBuffer 的insert()示例
*/
private static void testInsertAPIs() { System.out.println("-------------------------------- testInsertAPIs -------------------------------"); StringBuffer sbuilder = new StringBuffer(); // 在位置0处插入字符数组
sbuilder.insert(0, new char[]{'a','b','c','d','e'});
// 在位置0处插入字符数组。0表示字符数组起始位置,3表示长度
sbuilder.insert(0, new char[]{'A','B','C','D','E'}, 0, 3);
// 在位置0处插入float
sbuilder.insert(0, 1.414f);
// 在位置0处插入double
sbuilder.insert(0, 3.14159d);
// 在位置0处插入boolean
sbuilder.insert(0, true);
// 在位置0处插入char
sbuilder.insert(0, '\n');
// 在位置0处插入int
sbuilder.insert(0, 100);
// 在位置0处插入long
sbuilder.insert(0, 12345L);
// 在位置0处插入StringBuilder对象
sbuilder.insert(0, new StringBuffer("StringBuilder"));
// 在位置0处插入StringBuilder对象。6表示被在位置0处插入对象的起始位置(包括),13是结束位置(不包括)
sbuilder.insert(0, new StringBuffer("STRINGBUILDER"), 6, 13);
// 在位置0处插入StringBuffer对象。
sbuilder.insert(0, new StringBuffer("StringBuffer"));
// 在位置0处插入StringBuffer对象。6表示被在位置0处插入对象的起始位置(包括),12是结束位置(不包括)
sbuilder.insert(0, new StringBuffer("STRINGBUFFER"), 6, 12);
// 在位置0处插入String对象。
sbuilder.insert(0, "String");
// 在位置0处插入String对象。1表示被在位置0处插入对象的起始位置(包括),6是结束位置(不包括)
sbuilder.insert(0, "0123456789", 1, 6);
sbuilder.insert(0, '\n'); // 在位置0处插入Object对象。此处以HashMap为例
HashMap map = new HashMap();
map.put("1", "one");
map.put("2", "two");
map.put("3", "three");
sbuilder.insert(0, map); System.out.printf("%s\n\n", sbuilder);
} /**
* StringBuffer 的append()示例
*/
private static void testAppendAPIs() { System.out.println("-------------------------------- testAppendAPIs -------------------------------"); StringBuffer sbuilder = new StringBuffer(); // 追加字符数组
sbuilder.append(new char[]{'a','b','c','d','e'});
// 追加字符数组。0表示字符数组起始位置,3表示长度
sbuilder.append(new char[]{'A','B','C','D','E'}, 0, 3);
// 追加float
sbuilder.append(1.414f);
// 追加double
sbuilder.append(3.14159d);
// 追加boolean
sbuilder.append(true);
// 追加char
sbuilder.append('\n');
// 追加int
sbuilder.append(100);
// 追加long
sbuilder.append(12345L);
// 追加StringBuilder对象
sbuilder.append(new StringBuffer("StringBuilder"));
// 追加StringBuilder对象。6表示被追加对象的起始位置(包括),13是结束位置(不包括)
sbuilder.append(new StringBuffer("STRINGBUILDER"), 6, 13);
// 追加StringBuffer对象。
sbuilder.append(new StringBuffer("StringBuffer"));
// 追加StringBuffer对象。6表示被追加对象的起始位置(包括),12是结束位置(不包括)
sbuilder.append(new StringBuffer("STRINGBUFFER"), 6, 12);
// 追加String对象。
sbuilder.append("String");
// 追加String对象。1表示被追加对象的起始位置(包括),6是结束位置(不包括)
sbuilder.append("0123456789", 1, 6);
sbuilder.append('\n'); // 追加Object对象。此处以HashMap为例
HashMap map = new HashMap();
map.put("1", "one");
map.put("2", "two");
map.put("3", "three");
sbuilder.append(map);
sbuilder.append('\n'); // 追加unicode编码
sbuilder.appendCodePoint(0x5b57); // 0x5b57是“字”的unicode编码
sbuilder.appendCodePoint(0x7b26); // 0x7b26是“符”的unicode编码
sbuilder.appendCodePoint(0x7f16); // 0x7f16是“编”的unicode编码
sbuilder.appendCodePoint(0x7801); // 0x7801是“码”的unicode编码 System.out.printf("%s\n\n", sbuilder);
}
}

运行结果

-------------------------------- testInsertAPIs -------------------------------
{3=three, 2=two, 1=one}
12345StringBUFFERStringBufferBUILDERStringBuilder12345100
true3.141591.414ABCabcde -------------------------------- testAppendAPIs -------------------------------
abcdeABC1.4143.14159true
10012345StringBuilderBUILDERStringBufferBUFFERString12345
{3=three, 2=two, 1=one}
字符编码 -------------------------------- testReplaceAPIs ------------------------------
sbuilder=ABCDE3456789
sbuilder=9876543210
sbuilder=M123456789 -------------------------------- testDeleteAPIs -------------------------------
sbuilder=123789
str1=23789
str2=78
str3=78 -------------------------------- testIndexAPIs --------------------------------
sbuilder=abcAbcABCabCaBcAbCaBCabc
sbuilder.indexOf("bc") = 1
sbuilder.indexOf("bc", 5) = 22
sbuilder.lastIndexOf("bc") = 22
sbuilder.lastIndexOf("bc", 4) = 4 -------------------------------- testOtherAPIs --------------------------------
cap=26
c=6
carr[0]=3 carr[1]=4 carr[2]=5 carr[3]=6

 

StringBuffer 详解 (String系列之3)的更多相关文章

  1. StringBuilder 详解 (String系列之2)

    本章介绍StringBuilder以及它的API的详细使用方法. 转载请注明出处:http://www.cnblogs.com/skywang12345/p/string02.html StringB ...

  2. String详解, String和CharSequence区别, StringBuilder和StringBuffer的区别 (String系列之1)

    本章主要介绍String和CharSequence的区别,以及它们的API详细使用方法. 转载请注明出处:http://www.cnblogs.com/skywang12345/p/string01. ...

  3. String详解, String和CharSequence区别, StringBuilder和StringBuffer的区别

    本章主要介绍String和CharSequence的区别,以及它们的API详细使用方法. 转载请注明出处:http://www.cnblogs.com/skywang12345/p/string01. ...

  4. java基础(3)--详解String

    java基础(3)--详解String 其实与八大基本数据类型一样,String也是我们日常中使用非常频繁的对象,但知其然更要知其所以然,现在就去阅读源码深入了解一下String类对象,并解决一些我由 ...

  5. 「视频直播技术详解」系列之七:直播云 SDK 性能测试模型

    ​关于直播的技术文章不少,成体系的不多.我们将用七篇文章,更系统化地介绍当下大热的视频直播各环节的关键技术,帮助视频直播创业者们更全面.深入地了解视频直播技术,更好地技术选型. 本系列文章大纲如下: ...

  6. Swift_字符串详解(String)

    Swift_字符串详解(String) 类型别名 //类型别名 fileprivate func testTypeAliases() { let index = String.Index.self p ...

  7. 序列内置方法详解(string/list/tuple)

    一.常用方法集合 1.1.string,字符串常用方法 以下举例是python2.7测试: 函数名称 作用 举例 str.capitalize() 字符串第一个字符如果是字母,则把字母替换为大写字母. ...

  8. Java常用类StringBuffer详解

    内容多为最近学习的自我总结,可能有些地方写的不严谨,甚至会有错误的地方,仅供参考,如发现错误敬请指出,谢谢! 灰色字体为补充扩展内容,多为帮助自己理解. StringBuffer概述: 线程安全的可变 ...

  9. 【扯皮系列】一篇与众不同的 String、StringBuilder 和 StringBuffer 详解

    碎碎念 这是一道老生常谈的问题了,字符串是不仅是 Java 中非常重要的一个对象,它在其他语言中也存在.比如 C++.Visual Basic.C# 等.字符串使用 String 来表示,字符串一旦被 ...

随机推荐

  1. [Jmeter] Concurrency Thread Group

    Concurrency Thread Group : https://jmeter-plugins.org/wiki/ConcurrencyThreadGroup/ 参数介绍: Target Conc ...

  2. Fibonacci Number LT509

    The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such th ...

  3. mybatis 操作数据错误Truncated incorrect DOUBLE value: ''

    网上查到遇到次错误造成的原因: UPDATE TSYS_ROLE_RIGHTSET ACTIVE_FLAG = '2' and UPDATE_PERSON = 'CaiYiHua' and  UPDA ...

  4. jdom解析xml

    这次把代码整理了一下,打包发上来了,程序中需要用到的jar包也一起打在里面了,有兴趣的朋友可以解压后直接导入的eclipse里运行! xml是一种广为使用的可扩展标记语言,java中解析xml的方式有 ...

  5. Spring中@Autowired注解、@Resource注解的区别 (zz)

    Spring中@Autowired注解.@Resource注解的区别 Spring不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定义的注解,它们分别是@Resource.@ ...

  6. java script入门之知识

    1.注释 /*              */ 多行 //单行 2.常见形式 <!DOCTYPE html><html><head><title>My ...

  7. 初识kbmmw 5 中httpsys的支持

    前两天kbmmw 发布了5.0 版.里面一个非常令人兴奋的特性就是原生内部支持http.sys. 有关http.sys 的介绍及优势,我就在这里不多说了,大家可以参照一下我以前的文章. 关于http. ...

  8. 核心一:DI

    1.DI:中文名称:依赖注入 2.英文名称:(Dependency Injection) 3.DI是什么?? 3.1 DI和IoC是一样的 3.2 当一个类(A)中需要依赖另一类(B)对象时,把B赋值 ...

  9. 3、iOS Xcode创建protocol(代理).h文件

  10. shell 查询oracle数据库

    一个需求,做个监控脚本,监控一个表,把数据拉出了,处理一下,组成一个新的脚本,并执行. 直接上脚本: #!/bin/bash VALUE=`sqlplus "scott/trigger@or ...