本章介绍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)
1 package java.lang; 2 3 public final class StringBuffer 4 extends AbstractStringBuilder 5 implements java.io.Serializable, CharSequence 6 { 7 8 static final long serialVersionUID = 3388685877147921107L; 9 10 public StringBuffer() { 11 super(16); 12 } 13 14 public StringBuffer(int capacity) { 15 super(capacity); 16 } 17 18 public StringBuffer(String str) { 19 super(str.length() + 16); 20 append(str); 21 } 22 23 public StringBuffer(CharSequence seq) { 24 this(seq.length() + 16); 25 append(seq); 26 } 27 28 public synchronized int length() { 29 return count; 30 } 31 32 public synchronized int capacity() { 33 return value.length; 34 } 35 36 37 public synchronized void ensureCapacity(int minimumCapacity) { 38 if (minimumCapacity > value.length) { 39 expandCapacity(minimumCapacity); 40 } 41 } 42 43 public synchronized void trimToSize() { 44 super.trimToSize(); 45 } 46 47 public synchronized void setLength(int newLength) { 48 super.setLength(newLength); 49 } 50 51 public synchronized char charAt(int index) { 52 if ((index < 0) || (index >= count)) 53 throw new StringIndexOutOfBoundsException(index); 54 return value[index]; 55 } 56 57 public synchronized int codePointAt(int index) { 58 return super.codePointAt(index); 59 } 60 61 public synchronized int codePointBefore(int index) { 62 return super.codePointBefore(index); 63 } 64 65 public synchronized int codePointCount(int beginIndex, int endIndex) { 66 return super.codePointCount(beginIndex, endIndex); 67 } 68 69 public synchronized int offsetByCodePoints(int index, int codePointOffset) { 70 return super.offsetByCodePoints(index, codePointOffset); 71 } 72 73 public synchronized void getChars(int srcBegin, int srcEnd, char[] dst, 74 int dstBegin) 75 { 76 super.getChars(srcBegin, srcEnd, dst, dstBegin); 77 } 78 79 public synchronized void setCharAt(int index, char ch) { 80 if ((index < 0) || (index >= count)) 81 throw new StringIndexOutOfBoundsException(index); 82 value[index] = ch; 83 } 84 85 public synchronized StringBuffer append(Object obj) { 86 super.append(String.valueOf(obj)); 87 return this; 88 } 89 90 public synchronized StringBuffer append(String str) { 91 super.append(str); 92 return this; 93 } 94 95 public synchronized StringBuffer append(StringBuffer sb) { 96 super.append(sb); 97 return this; 98 } 99 100 public StringBuffer append(CharSequence s) { 101 // Note, synchronization achieved via other invocations 102 if (s == null) 103 s = "null"; 104 if (s instanceof String) 105 return this.append((String)s); 106 if (s instanceof StringBuffer) 107 return this.append((StringBuffer)s); 108 return this.append(s, 0, s.length()); 109 } 110 111 public synchronized StringBuffer append(CharSequence s, int start, int end) 112 { 113 super.append(s, start, end); 114 return this; 115 } 116 117 public synchronized StringBuffer append(char[] str) { 118 super.append(str); 119 return this; 120 } 121 122 public synchronized StringBuffer append(char[] str, int offset, int len) { 123 super.append(str, offset, len); 124 return this; 125 } 126 127 public synchronized StringBuffer append(boolean b) { 128 super.append(b); 129 return this; 130 } 131 132 public synchronized StringBuffer append(char c) { 133 super.append(c); 134 return this; 135 } 136 137 public synchronized StringBuffer append(int i) { 138 super.append(i); 139 return this; 140 } 141 142 public synchronized StringBuffer appendCodePoint(int codePoint) { 143 super.appendCodePoint(codePoint); 144 return this; 145 } 146 147 public synchronized StringBuffer append(long lng) { 148 super.append(lng); 149 return this; 150 } 151 152 public synchronized StringBuffer append(float f) { 153 super.append(f); 154 return this; 155 } 156 157 public synchronized StringBuffer append(double d) { 158 super.append(d); 159 return this; 160 } 161 162 public synchronized StringBuffer delete(int start, int end) { 163 super.delete(start, end); 164 return this; 165 } 166 167 public synchronized StringBuffer deleteCharAt(int index) { 168 super.deleteCharAt(index); 169 return this; 170 } 171 172 public synchronized StringBuffer replace(int start, int end, String str) { 173 super.replace(start, end, str); 174 return this; 175 } 176 177 public synchronized String substring(int start) { 178 return substring(start, count); 179 } 180 181 public synchronized CharSequence subSequence(int start, int end) { 182 return super.substring(start, end); 183 } 184 185 public synchronized String substring(int start, int end) { 186 return super.substring(start, end); 187 } 188 189 public synchronized StringBuffer insert(int index, char[] str, int offset, 190 int len) 191 { 192 super.insert(index, str, offset, len); 193 return this; 194 } 195 196 public synchronized StringBuffer insert(int offset, Object obj) { 197 super.insert(offset, String.valueOf(obj)); 198 return this; 199 } 200 201 public synchronized StringBuffer insert(int offset, String str) { 202 super.insert(offset, str); 203 return this; 204 } 205 206 public synchronized StringBuffer insert(int offset, char[] str) { 207 super.insert(offset, str); 208 return this; 209 } 210 211 public StringBuffer insert(int dstOffset, CharSequence s) { 212 // Note, synchronization achieved via other invocations 213 if (s == null) 214 s = "null"; 215 if (s instanceof String) 216 return this.insert(dstOffset, (String)s); 217 return this.insert(dstOffset, s, 0, s.length()); 218 } 219 220 public synchronized StringBuffer insert(int dstOffset, CharSequence s, 221 int start, int end) 222 { 223 super.insert(dstOffset, s, start, end); 224 return this; 225 } 226 227 public StringBuffer insert(int offset, boolean b) { 228 return insert(offset, String.valueOf(b)); 229 } 230 231 public synchronized StringBuffer insert(int offset, char c) { 232 super.insert(offset, c); 233 return this; 234 } 235 236 public StringBuffer insert(int offset, int i) { 237 return insert(offset, String.valueOf(i)); 238 } 239 240 public StringBuffer insert(int offset, long l) { 241 return insert(offset, String.valueOf(l)); 242 } 243 244 public StringBuffer insert(int offset, float f) { 245 return insert(offset, String.valueOf(f)); 246 } 247 248 public StringBuffer insert(int offset, double d) { 249 return insert(offset, String.valueOf(d)); 250 } 251 252 public int indexOf(String str) { 253 return indexOf(str, 0); 254 } 255 256 public synchronized int indexOf(String str, int fromIndex) { 257 return String.indexOf(value, 0, count, 258 str.toCharArray(), 0, str.length(), fromIndex); 259 } 260 261 public int lastIndexOf(String str) { 262 // Note, synchronization achieved via other invocations 263 return lastIndexOf(str, count); 264 } 265 266 public synchronized int lastIndexOf(String str, int fromIndex) { 267 return String.lastIndexOf(value, 0, count, 268 str.toCharArray(), 0, str.length(), fromIndex); 269 } 270 271 public synchronized StringBuffer reverse() { 272 super.reverse(); 273 return this; 274 } 275 276 public synchronized String toString() { 277 return new String(value, 0, count); 278 } 279 280 private static final java.io.ObjectStreamField[] serialPersistentFields = 281 { 282 new java.io.ObjectStreamField("value", char[].class), 283 new java.io.ObjectStreamField("count", Integer.TYPE), 284 new java.io.ObjectStreamField("shared", Boolean.TYPE), 285 }; 286 287 private synchronized void writeObject(java.io.ObjectOutputStream s) 288 throws java.io.IOException { 289 java.io.ObjectOutputStream.PutField fields = s.putFields(); 290 fields.put("value", value); 291 fields.put("count", count); 292 fields.put("shared", false); 293 s.writeFields(); 294 } 295 296 private void readObject(java.io.ObjectInputStream s) 297 throws java.io.IOException, ClassNotFoundException { 298 java.io.ObjectInputStream.GetField fields = s.readFields(); 299 value = (char[])fields.get("value", null); 300 count = fields.get("count", 0); 301 } 302 }
StringBuffer 示例
源码如下(StringBufferTest.java):
1 /** 2 * StringBuffer 演示程序 3 * 4 * @author skywang 5 */ 6 import java.util.HashMap; 7 8 public class StringBufferTest { 9 10 public static void main(String[] args) { 11 testInsertAPIs() ; 12 testAppendAPIs() ; 13 testReplaceAPIs() ; 14 testDeleteAPIs() ; 15 testIndexAPIs() ; 16 testOtherAPIs() ; 17 } 18 19 /** 20 * StringBuffer 的其它API示例 21 */ 22 private static void testOtherAPIs() { 23 24 System.out.println("-------------------------------- testOtherAPIs --------------------------------"); 25 26 StringBuffer sbuilder = new StringBuffer("0123456789"); 27 28 int cap = sbuilder.capacity(); 29 System.out.printf("cap=%d\n", cap); 30 31 char c = sbuilder.charAt(6); 32 System.out.printf("c=%c\n", c); 33 34 char[] carr = new char[4]; 35 sbuilder.getChars(3, 7, carr, 0); 36 for (int i=0; i<carr.length; i++) 37 System.out.printf("carr[%d]=%c ", i, carr[i]); 38 System.out.println(); 39 40 System.out.println(); 41 } 42 43 /** 44 * StringBuffer 中index相关API演示 45 */ 46 private static void testIndexAPIs() { 47 System.out.println("-------------------------------- testIndexAPIs --------------------------------"); 48 49 StringBuffer sbuilder = new StringBuffer("abcAbcABCabCaBcAbCaBCabc"); 50 System.out.printf("sbuilder=%s\n", sbuilder); 51 52 // 1. 从前往后,找出"bc"第一次出现的位置 53 System.out.printf("%-30s = %d\n", "sbuilder.indexOf(\"bc\")", sbuilder.indexOf("bc")); 54 55 // 2. 从位置5开始,从前往后,找出"bc"第一次出现的位置 56 System.out.printf("%-30s = %d\n", "sbuilder.indexOf(\"bc\", 5)", sbuilder.indexOf("bc", 5)); 57 58 // 3. 从后往前,找出"bc"第一次出现的位置 59 System.out.printf("%-30s = %d\n", "sbuilder.lastIndexOf(\"bc\")", sbuilder.lastIndexOf("bc")); 60 61 // 4. 从位置4开始,从后往前,找出"bc"第一次出现的位置 62 System.out.printf("%-30s = %d\n", "sbuilder.lastIndexOf(\"bc\", 4)", sbuilder.lastIndexOf("bc", 4)); 63 64 System.out.println(); 65 } 66 67 /** 68 * StringBuffer 的replace()示例 69 */ 70 private static void testReplaceAPIs() { 71 72 System.out.println("-------------------------------- testReplaceAPIs ------------------------------"); 73 74 StringBuffer sbuilder; 75 76 sbuilder = new StringBuffer("0123456789"); 77 sbuilder.replace(0, 3, "ABCDE"); 78 System.out.printf("sbuilder=%s\n", sbuilder); 79 80 sbuilder = new StringBuffer("0123456789"); 81 sbuilder.reverse(); 82 System.out.printf("sbuilder=%s\n", sbuilder); 83 84 sbuilder = new StringBuffer("0123456789"); 85 sbuilder.setCharAt(0, 'M'); 86 System.out.printf("sbuilder=%s\n", sbuilder); 87 88 System.out.println(); 89 } 90 91 /** 92 * StringBuffer 的delete()示例 93 */ 94 private static void testDeleteAPIs() { 95 96 System.out.println("-------------------------------- testDeleteAPIs -------------------------------"); 97 98 StringBuffer sbuilder = new StringBuffer("0123456789"); 99 100 // 删除位置0的字符,剩余字符是“123456789”。 101 sbuilder.deleteCharAt(0); 102 // 删除位置3(包括)到位置6(不包括)之间的字符,剩余字符是“123789”。 103 sbuilder.delete(3,6); 104 105 // 获取sb中从位置1开始的字符串 106 String str1 = sbuilder.substring(1); 107 // 获取sb中从位置3(包括)到位置5(不包括)之间的字符串 108 String str2 = sbuilder.substring(3, 5); 109 // 获取sb中从位置3(包括)到位置5(不包括)之间的字符串,获取的对象是CharSequence对象,此处转型为String 110 String str3 = (String)sbuilder.subSequence(3, 5); 111 112 System.out.printf("sbuilder=%s\nstr1=%s\nstr2=%s\nstr3=%s\n", 113 sbuilder, str1, str2, str3); 114 115 System.out.println(); 116 } 117 118 /** 119 * StringBuffer 的insert()示例 120 */ 121 private static void testInsertAPIs() { 122 123 System.out.println("-------------------------------- testInsertAPIs -------------------------------"); 124 125 StringBuffer sbuilder = new StringBuffer(); 126 127 // 在位置0处插入字符数组 128 sbuilder.insert(0, new char[]{'a','b','c','d','e'}); 129 // 在位置0处插入字符数组。0表示字符数组起始位置,3表示长度 130 sbuilder.insert(0, new char[]{'A','B','C','D','E'}, 0, 3); 131 // 在位置0处插入float 132 sbuilder.insert(0, 1.414f); 133 // 在位置0处插入double 134 sbuilder.insert(0, 3.14159d); 135 // 在位置0处插入boolean 136 sbuilder.insert(0, true); 137 // 在位置0处插入char 138 sbuilder.insert(0, '\n'); 139 // 在位置0处插入int 140 sbuilder.insert(0, 100); 141 // 在位置0处插入long 142 sbuilder.insert(0, 12345L); 143 // 在位置0处插入StringBuilder对象 144 sbuilder.insert(0, new StringBuffer("StringBuilder")); 145 // 在位置0处插入StringBuilder对象。6表示被在位置0处插入对象的起始位置(包括),13是结束位置(不包括) 146 sbuilder.insert(0, new StringBuffer("STRINGBUILDER"), 6, 13); 147 // 在位置0处插入StringBuffer对象。 148 sbuilder.insert(0, new StringBuffer("StringBuffer")); 149 // 在位置0处插入StringBuffer对象。6表示被在位置0处插入对象的起始位置(包括),12是结束位置(不包括) 150 sbuilder.insert(0, new StringBuffer("STRINGBUFFER"), 6, 12); 151 // 在位置0处插入String对象。 152 sbuilder.insert(0, "String"); 153 // 在位置0处插入String对象。1表示被在位置0处插入对象的起始位置(包括),6是结束位置(不包括) 154 sbuilder.insert(0, "0123456789", 1, 6); 155 sbuilder.insert(0, '\n'); 156 157 // 在位置0处插入Object对象。此处以HashMap为例 158 HashMap map = new HashMap(); 159 map.put("1", "one"); 160 map.put("2", "two"); 161 map.put("3", "three"); 162 sbuilder.insert(0, map); 163 164 System.out.printf("%s\n\n", sbuilder); 165 } 166 167 /** 168 * StringBuffer 的append()示例 169 */ 170 private static void testAppendAPIs() { 171 172 System.out.println("-------------------------------- testAppendAPIs -------------------------------"); 173 174 StringBuffer sbuilder = new StringBuffer(); 175 176 // 追加字符数组 177 sbuilder.append(new char[]{'a','b','c','d','e'}); 178 // 追加字符数组。0表示字符数组起始位置,3表示长度 179 sbuilder.append(new char[]{'A','B','C','D','E'}, 0, 3); 180 // 追加float 181 sbuilder.append(1.414f); 182 // 追加double 183 sbuilder.append(3.14159d); 184 // 追加boolean 185 sbuilder.append(true); 186 // 追加char 187 sbuilder.append('\n'); 188 // 追加int 189 sbuilder.append(100); 190 // 追加long 191 sbuilder.append(12345L); 192 // 追加StringBuilder对象 193 sbuilder.append(new StringBuffer("StringBuilder")); 194 // 追加StringBuilder对象。6表示被追加对象的起始位置(包括),13是结束位置(不包括) 195 sbuilder.append(new StringBuffer("STRINGBUILDER"), 6, 13); 196 // 追加StringBuffer对象。 197 sbuilder.append(new StringBuffer("StringBuffer")); 198 // 追加StringBuffer对象。6表示被追加对象的起始位置(包括),12是结束位置(不包括) 199 sbuilder.append(new StringBuffer("STRINGBUFFER"), 6, 12); 200 // 追加String对象。 201 sbuilder.append("String"); 202 // 追加String对象。1表示被追加对象的起始位置(包括),6是结束位置(不包括) 203 sbuilder.append("0123456789", 1, 6); 204 sbuilder.append('\n'); 205 206 // 追加Object对象。此处以HashMap为例 207 HashMap map = new HashMap(); 208 map.put("1", "one"); 209 map.put("2", "two"); 210 map.put("3", "three"); 211 sbuilder.append(map); 212 sbuilder.append('\n'); 213 214 // 追加unicode编码 215 sbuilder.appendCodePoint(0x5b57); // 0x5b57是“字”的unicode编码 216 sbuilder.appendCodePoint(0x7b26); // 0x7b26是“符”的unicode编码 217 sbuilder.appendCodePoint(0x7f16); // 0x7f16是“编”的unicode编码 218 sbuilder.appendCodePoint(0x7801); // 0x7801是“码”的unicode编码 219 220 System.out.printf("%s\n\n", sbuilder); 221 } 222 }
运行结果:
-------------------------------- 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