JAVA_String、StringBuffer、StringBuilder_三者差異與記憶體內部運行機制介紹_雙等號與equals差別
【結論】
效能上
StringBulder(無Thread-Safe)
快於 StringBuffer(有Thread-Safe)
快於 String(會於內部轉為StringBuffer進行較多記憶體運算)
當你在做一些純粹針對 值或內容比對是否一樣時
請愛用 .equals()
盡量不要用雙等號
雙等號會多判斷是否參照到相同物件
【細部實作過程推導】
日常JAVA開發工作中最常碰到的就是我們所謂的
字串的相關處裡
這次要先來介紹關於
String 相關物件的運作差異
=============================================================
1. String
2. StringBuffer
3. StringBuilder
=============================================================
1. String 宣告寫法
在一般String 宣告時
多數JAVA程式設計師
會直接用來作為變數指派
在JAVA 官方API 文件上
可以查到 其實它有許多建構子的多載
這邊先來看一段作為一般變數時指派內部運作細節
code 區塊
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package stringtest1; /** * * @author chous */ public class StringTest1 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here System.out.println("==========String物件作為一般變數指派============="); String s = "Hello"; System.out.println("s:" + s); String s1 = "Hello"; System.out.println("s1:" +s1); String s2 = "Hi"; System.out.println("s2:" +s2); System.out.println("s == s1: " + (s == s1) ); System.out.println("s.equals(s1): " + s.equals(s1)); } } |
當你指派好一個字串內容值給String變數值時
記憶體內部會配置一個記憶體空間存放對應結果
那由於是採用一般變數指派所以會存於共享資源池的記憶體中
當你指派的值有重複時則會直接指向相同記憶體空間位址
所以目前無論是 s 或 s1 都是指向相同memory location
只有在指派不同內容時才會生出一個全新記憶體空間
並指向新位址到底剛剛所用的 雙等號 與 equals 差別在哪呢??
這邊我們在嘗試使用 JAVA 作為物件實體來指派值運作結果輸出
code區塊
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javastr1; /** * * @author chous */ public class JAVAStr1 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here System.out.println("==========String物件作為一般變數指派============="); String s = "Hello"; System.out.println("s:" + s); String s1 = "Hello"; System.out.println("s1:" +s1); String s2 = "Hi"; System.out.println("s2:" +s2); System.out.println("s == s1: " + (s == s1) ); System.out.println("s.equals(s1): " + s.equals(s1)); System.out.println("==========String物件作為物件實體生成(不同記憶體位址)============="); System.out.println("雙等號(會看記憶體位址)_equals(只要值相同就好)"); String strObj1 = new String("Hello"); System.out.println("strObj1: " + strObj1); System.out.println("s == strObj1: " + (s == strObj1)); System.out.println("s.equals(strObj1): " + s.equals(strObj1)); System.out.println("======================="); String strObj2 = new String("Hello"); System.out.println("strObj2: " + strObj2); System.out.println("strObj1 == strObj2: " + (strObj1 == strObj2)); System.out.println("strObj1.equals(strObj2): " + strObj1.equals(strObj2)); } } |
當String 作為 物件來使用
則會因為創出不同實體而有不同的物件記憶體位址也被配置出來
所以若在此使用 雙等號即可明確看出差異
到底String 和 StringBuffer 差別在哪
何時用哪個??
事實上 String 物件是不可變動的!!!!
String Object is immutable !!!
而 StringBuffer 是可異動、同步更新的!!
StringBuffer Object is mutable !!!
code 區塊
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javastrtest2; /** * * @author chous */ public class JAVAStrTest2 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here String s = new String("Hello"); System.out.println("s:" + s +" ,s的記憶體位址(物件編碼):" + s.hashCode()); s+= "Hi"; System.out.println("s:" + s+" ,s的記憶體位址(物件編碼):" + s.hashCode()); System.out.println("==============================="); StringBuffer s2 = new StringBuffer("Hello"); System.out.println("s2:" + s2 + ",s2的記憶體位址(物件編碼):" + s2.hashCode()); s2.append("Hi"); System.out.println("s2:" + s2 + ",s2的記憶體位址(物件編碼):" + s2.hashCode()); } } |
這邊我們用字串串接為示意範本!!!
String 物件 做串接使用 +=
StringBuffer 物件 則使用 .append()
這邊事實上我們無法在JAVA中透過內定方法獲取實際記憶體位址
頂多只能使用 hashcode 回傳的物件編碼
來判斷參照到的物件是否一致
這邊會看到運行出來結果實際上
StringBuffer一直都是指向同一物件
然而
String物件
其實在內部已經又生出另一個新位址來存放串接後的內容結果
並指向另一個新位址
String 和 StringBuffer 誰比較快呢???
事實上JAVA String 做字串串接時
表面上看語法是透過簡單 "加號" 來實踐
和 StringBuffer 物件 使用到的 .append()方法
看似一樣效果
實際底層運作過程
String 在使用 "+" 做字串串接時
1.會先轉為 StringBuffer 物件
2.再去call一次 .append() 方法
3.最後再將StringBuffer 資料型態轉為 String
所以你會看到它比StringBuffer於記憶體內部做了更多動作
因此較為耗時!!!!!
StringBuffer 於記憶體底層運算會比String 更精簡
StringBuffer 和 StringBuilder 差異
事實上若有看過JAVA 官方說明裡頭
你會發現這兩個物件的方法大同小異
彼此若於實體化時給予空值
預設皆設定16為大小
CODE 區塊
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package teststrapp; /** * * @author chous */ public class TestStrApp { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here System.out.println("=================StringBuilder預設資料空間&字串長==================="); StringBuilder sbd0 = new StringBuilder(); System.out.println("StringBuilder初始空內容(sbd0):"+ sbd0.toString()); System.out.println("StringBuilder預設資料空間大小(sbd0):" + sbd0.capacity()); System.out.println("StringBuilder預設字串長度(sbd0):" + sbd0.length()); System.out.println("=================StringBuffer預設資料空間&字串長==================="); StringBuffer sbf0 = new StringBuffer(); System.out.println("StringBuffer初始空內容(sbf0):"+ sbf0.toString()); System.out.println("StringBuffer預設資料空間大小(sbf0):" + sbf0.capacity()); System.out.println("StringBuffer預設字串長度(sbf0):" + sbf0.length()); System.out.println("=================StringBuilder串接新字元後之資料空間&字串長更動==================="); sbd0.append("a"); System.out.println("StringBuilder內容(sbd0):"+ sbd0.toString()); System.out.println("StringBuilder資料空間大小(sbd0):" + sbd0.capacity()); System.out.println("StringBuilder字串長度(sbd0):" + sbd0.length()); sbd0.append("b"); System.out.println("StringBuilder內容(sbd0):"+ sbd0.toString()); System.out.println("StringBuilder資料空間大小(sbd0):" + sbd0.capacity()); System.out.println("StringBuilder字串長度(sbd0):" + sbd0.length()); sbd0.append("c"); System.out.println("StringBuilder內容(sbd0):"+ sbd0.toString()); System.out.println("StringBuilder資料空間大小(sbd0):" + sbd0.capacity()); System.out.println("StringBuilder字串長度(sbd0):" + sbd0.length()); System.out.println("=================StringBuffer串接新字元後之資料空間&字串長更動==================="); sbf0.append("a"); System.out.println("StringBuffer內容(sbf0):"+ sbf0.toString()); System.out.println("StringBuffer資料空間大小(sbf0):" + sbf0.capacity()); System.out.println("StringBuffer字串長度(sbf0):" + sbf0.length()); sbf0.append("b"); System.out.println("StringBuffer內容(sbf0):"+ sbf0.toString()); System.out.println("StringBuffer資料空間大小(sbf0):" + sbf0.capacity()); System.out.println("StringBuffer字串長度(sbf0):" + sbf0.length()); sbf0.append("c"); System.out.println("StringBuffer內容(sbf0):"+ sbf0.toString()); System.out.println("StringBuffer資料空間大小(sbf0):" + sbf0.capacity()); System.out.println("StringBuffer字串長度(sbf0):" + sbf0.length()); System.out.println("=================StringBuilder字串反序==================="); StringBuilder sbd1 = new StringBuilder("ABC"); System.out.println("StringBuilder 資料大小(sbd1):" +sbd1.capacity()); System.out.println("StringBuilder 字串長(sbd1):" +sbd1.length()); System.out.println("StringBuilder(sbd1):" + sbd1.toString()); sbd1.reverse(); System.out.println("StringBuilder 反轉後(sbd1):" +sbd1.toString()); System.out.println("=================StringBuffer字串反序==================="); StringBuffer sbf1 = new StringBuffer("ABC"); System.out.println("StringBuffer 資料大小(sbf1):" +sbf1.capacity()); System.out.println("StringBuffer 字串長(sbf1):" +sbf1.length()); System.out.println("StringBuffer(sbf1):" +sbf1.toString()); sbf1.reverse(); System.out.println("StringBuffer 反轉後(sbf1):" +sbf1.toString()); } } |
差異在於
StringBuilder 屬於 Thread-Not-Safe 底層則沒有使用Synchronized機制
StringBuffer 屬於 Thread-Safe 底層代碼會使用Synchronized避免死結發生
StringBuilder 底層code(沒有任何Synchronized字眼)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 | /* * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.lang; /** * A mutable sequence of characters. This class provides an API compatible * with {@code StringBuffer}, but with no guarantee of synchronization. * This class is designed for use as a drop-in replacement for * {@code StringBuffer} in places where the string buffer was being * used by a single thread (as is generally the case). Where possible, * it is recommended that this class be used in preference to * {@code StringBuffer} as it will be faster under most implementations. * * <p>The principal operations on a {@code StringBuilder} are the * {@code append} and {@code insert} methods, which are * overloaded so as to accept data of any type. Each effectively * converts a given datum to a string and then appends or inserts the * characters of that string to the string builder. The * {@code append} method always adds these characters at the end * of the builder; the {@code insert} method adds the characters at * a specified point. * <p> * For example, if {@code z} refers to a string builder object * whose current contents are "{@code start}", then * the method call {@code z.append("le")} would cause the string * builder to contain "{@code startle}", whereas * {@code z.insert(4, "le")} would alter the string builder to * contain "{@code starlet}". * <p> * In general, if sb refers to an instance of a {@code StringBuilder}, * then {@code sb.append(x)} has the same effect as * {@code sb.insert(sb.length(), x)}. * <p> * Every string builder has a capacity. As long as the length of the * character sequence contained in the string builder does not exceed * the capacity, it is not necessary to allocate a new internal * buffer. If the internal buffer overflows, it is automatically made larger. * * <p>Instances of {@code StringBuilder} are not safe for * use by multiple threads. If such synchronization is required then it is * recommended that {@link java.lang.StringBuffer} be used. * * <p>Unless otherwise noted, passing a {@code null} argument to a constructor * or method in this class will cause a {@link NullPointerException} to be * thrown. * * @author Michael McCloskey * @see java.lang.StringBuffer * @see java.lang.String * @since 1.5 */ public final class StringBuilder extends AbstractStringBuilder implements java.io.Serializable, CharSequence { /** use serialVersionUID for interoperability */ static final long serialVersionUID = 4383685877147921099L; /** * Constructs a string builder with no characters in it and an * initial capacity of 16 characters. */ public StringBuilder() { super(16); } /** * Constructs a string builder with no characters in it and an * initial capacity specified by the {@code capacity} argument. * * @param capacity the initial capacity. * @throws NegativeArraySizeException if the {@code capacity} * argument is less than {@code 0}. */ public StringBuilder(int capacity) { super(capacity); } /** * Constructs a string builder initialized to the contents of the * specified string. The initial capacity of the string builder is * {@code 16} plus the length of the string argument. * * @param str the initial contents of the buffer. */ public StringBuilder(String str) { super(str.length() + 16); append(str); } /** * Constructs a string builder that contains the same characters * as the specified {@code CharSequence}. The initial capacity of * the string builder is {@code 16} plus the length of the * {@code CharSequence} argument. * * @param seq the sequence to copy. */ public StringBuilder(CharSequence seq) { this(seq.length() + 16); append(seq); } @Override public StringBuilder append(Object obj) { return append(String.valueOf(obj)); } @Override public StringBuilder append(String str) { super.append(str); return this; } /** * Appends the specified {@code StringBuffer} to this sequence. * <p> * The characters of the {@code StringBuffer} argument are appended, * in order, to this sequence, increasing the * length of this sequence by the length of the argument. * If {@code sb} is {@code null}, then the four characters * {@code "null"} are appended to this sequence. * <p> * Let <i>n</i> be the length of this character sequence just prior to * execution of the {@code append} method. Then the character at index * <i>k</i> in the new character sequence is equal to the character at * index <i>k</i> in the old character sequence, if <i>k</i> is less than * <i>n</i>; otherwise, it is equal to the character at index <i>k-n</i> * in the argument {@code sb}. * * @param sb the {@code StringBuffer} to append. * @return a reference to this object. */ public StringBuilder append(StringBuffer sb) { super.append(sb); return this; } @Override public StringBuilder append(CharSequence s) { super.append(s); return this; } /** * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder append(CharSequence s, int start, int end) { super.append(s, start, end); return this; } @Override public StringBuilder append(char[] str) { super.append(str); return this; } /** * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder append(char[] str, int offset, int len) { super.append(str, offset, len); return this; } @Override public StringBuilder append(boolean b) { super.append(b); return this; } @Override public StringBuilder append(char c) { super.append(c); return this; } @Override public StringBuilder append(int i) { super.append(i); return this; } @Override public StringBuilder append(long lng) { super.append(lng); return this; } @Override public StringBuilder append(float f) { super.append(f); return this; } @Override public StringBuilder append(double d) { super.append(d); return this; } /** * @since 1.5 */ @Override public StringBuilder appendCodePoint(int codePoint) { super.appendCodePoint(codePoint); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder delete(int start, int end) { super.delete(start, end); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder deleteCharAt(int index) { super.deleteCharAt(index); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder replace(int start, int end, String str) { super.replace(start, end, str); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder insert(int index, char[] str, int offset, int len) { super.insert(index, str, offset, len); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder insert(int offset, Object obj) { super.insert(offset, obj); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder insert(int offset, String str) { super.insert(offset, str); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder insert(int offset, char[] str) { super.insert(offset, str); return this; } /** * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder insert(int dstOffset, CharSequence s) { super.insert(dstOffset, s); return this; } /** * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder insert(int dstOffset, CharSequence s, int start, int end) { super.insert(dstOffset, s, start, end); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder insert(int offset, boolean b) { super.insert(offset, b); return this; } /** * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder insert(int offset, char c) { super.insert(offset, c); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder insert(int offset, int i) { super.insert(offset, i); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder insert(int offset, long l) { super.insert(offset, l); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder insert(int offset, float f) { super.insert(offset, f); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuilder insert(int offset, double d) { super.insert(offset, d); return this; } @Override public int indexOf(String str) { return super.indexOf(str); } @Override public int indexOf(String str, int fromIndex) { return super.indexOf(str, fromIndex); } @Override public int lastIndexOf(String str) { return super.lastIndexOf(str); } @Override public int lastIndexOf(String str, int fromIndex) { return super.lastIndexOf(str, fromIndex); } @Override public StringBuilder reverse() { super.reverse(); return this; } @Override public String toString() { // Create a copy, don't share the array return new String(value, 0, count); } /** * Save the state of the {@code StringBuilder} instance to a stream * (that is, serialize it). * * @serialData the number of characters currently stored in the string * builder ({@code int}), followed by the characters in the * string builder ({@code char[]}). The length of the * {@code char} array may be greater than the number of * characters currently stored in the string builder, in which * case extra characters are ignored. */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { s.defaultWriteObject(); s.writeInt(count); s.writeObject(value); } /** * readObject is called to restore the state of the StringBuffer from * a stream. */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); count = s.readInt(); value = (char[]) s.readObject(); } } |
StringBuffer 底層code(有Synchronized字眼)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 | /* * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.lang; import java.util.Arrays; /** * A thread-safe, mutable sequence of characters. * A string buffer is like a {@link String}, but can be modified. At any * point in time it contains some particular sequence of characters, but * the length and content of the sequence can be changed through certain * method calls. * <p> * String buffers are safe for use by multiple threads. The methods * are synchronized where necessary so that all the operations on any * particular instance behave as if they occur in some serial order * that is consistent with the order of the method calls made by each of * the individual threads involved. * <p> * The principal operations on a {@code StringBuffer} are the * {@code append} and {@code insert} methods, which are * overloaded so as to accept data of any type. Each effectively * converts a given datum to a string and then appends or inserts the * characters of that string to the string buffer. The * {@code append} method always adds these characters at the end * of the buffer; the {@code insert} method adds the characters at * a specified point. * <p> * For example, if {@code z} refers to a string buffer object * whose current contents are {@code "start"}, then * the method call {@code z.append("le")} would cause the string * buffer to contain {@code "startle"}, whereas * {@code z.insert(4, "le")} would alter the string buffer to * contain {@code "starlet"}. * <p> * In general, if sb refers to an instance of a {@code StringBuffer}, * then {@code sb.append(x)} has the same effect as * {@code sb.insert(sb.length(), x)}. * <p> * Whenever an operation occurs involving a source sequence (such as * appending or inserting from a source sequence), this class synchronizes * only on the string buffer performing the operation, not on the source. * Note that while {@code StringBuffer} is designed to be safe to use * concurrently from multiple threads, if the constructor or the * {@code append} or {@code insert} operation is passed a source sequence * that is shared across threads, the calling code must ensure * that the operation has a consistent and unchanging view of the source * sequence for the duration of the operation. * This could be satisfied by the caller holding a lock during the * operation's call, by using an immutable source sequence, or by not * sharing the source sequence across threads. * <p> * Every string buffer has a capacity. As long as the length of the * character sequence contained in the string buffer does not exceed * the capacity, it is not necessary to allocate a new internal * buffer array. If the internal buffer overflows, it is * automatically made larger. * <p> * Unless otherwise noted, passing a {@code null} argument to a constructor * or method in this class will cause a {@link NullPointerException} to be * thrown. * <p> * As of release JDK 5, this class has been supplemented with an equivalent * class designed for use by a single thread, {@link StringBuilder}. The * {@code StringBuilder} class should generally be used in preference to * this one, as it supports all of the same operations but it is faster, as * it performs no synchronization. * * @author Arthur van Hoff * @see java.lang.StringBuilder * @see java.lang.String * @since JDK1.0 */ public final class StringBuffer extends AbstractStringBuilder implements java.io.Serializable, CharSequence { /** * A cache of the last value returned by toString. Cleared * whenever the StringBuffer is modified. */ private transient char[] toStringCache; /** use serialVersionUID from JDK 1.0.2 for interoperability */ static final long serialVersionUID = 3388685877147921107L; /** * Constructs a string buffer with no characters in it and an * initial capacity of 16 characters. */ public StringBuffer() { super(16); } /** * Constructs a string buffer with no characters in it and * the specified initial capacity. * * @param capacity the initial capacity. * @exception NegativeArraySizeException if the {@code capacity} * argument is less than {@code 0}. */ public StringBuffer(int capacity) { super(capacity); } /** * Constructs a string buffer initialized to the contents of the * specified string. The initial capacity of the string buffer is * {@code 16} plus the length of the string argument. * * @param str the initial contents of the buffer. */ public StringBuffer(String str) { super(str.length() + 16); append(str); } /** * Constructs a string buffer that contains the same characters * as the specified {@code CharSequence}. The initial capacity of * the string buffer is {@code 16} plus the length of the * {@code CharSequence} argument. * <p> * If the length of the specified {@code CharSequence} is * less than or equal to zero, then an empty buffer of capacity * {@code 16} is returned. * * @param seq the sequence to copy. * @since 1.5 */ public StringBuffer(CharSequence seq) { this(seq.length() + 16); append(seq); } @Override public synchronized int length() { return count; } @Override public synchronized int capacity() { return value.length; } @Override public synchronized void ensureCapacity(int minimumCapacity) { super.ensureCapacity(minimumCapacity); } /** * @since 1.5 */ @Override public synchronized void trimToSize() { super.trimToSize(); } /** * @throws IndexOutOfBoundsException {@inheritDoc} * @see #length() */ @Override public synchronized void setLength(int newLength) { toStringCache = null; super.setLength(newLength); } /** * @throws IndexOutOfBoundsException {@inheritDoc} * @see #length() */ @Override public synchronized char charAt(int index) { if ((index < 0) || (index >= count)) throw new StringIndexOutOfBoundsException(index); return value[index]; } /** * @since 1.5 */ @Override public synchronized int codePointAt(int index) { return super.codePointAt(index); } /** * @since 1.5 */ @Override public synchronized int codePointBefore(int index) { return super.codePointBefore(index); } /** * @since 1.5 */ @Override public synchronized int codePointCount(int beginIndex, int endIndex) { return super.codePointCount(beginIndex, endIndex); } /** * @since 1.5 */ @Override public synchronized int offsetByCodePoints(int index, int codePointOffset) { return super.offsetByCodePoints(index, codePointOffset); } /** * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public synchronized void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) { super.getChars(srcBegin, srcEnd, dst, dstBegin); } /** * @throws IndexOutOfBoundsException {@inheritDoc} * @see #length() */ @Override public synchronized void setCharAt(int index, char ch) { if ((index < 0) || (index >= count)) throw new StringIndexOutOfBoundsException(index); toStringCache = null; value[index] = ch; } @Override public synchronized StringBuffer append(Object obj) { toStringCache = null; super.append(String.valueOf(obj)); return this; } @Override public synchronized StringBuffer append(String str) { toStringCache = null; super.append(str); return this; } /** * Appends the specified {@code StringBuffer} to this sequence. * <p> * The characters of the {@code StringBuffer} argument are appended, * in order, to the contents of this {@code StringBuffer}, increasing the * length of this {@code StringBuffer} by the length of the argument. * If {@code sb} is {@code null}, then the four characters * {@code "null"} are appended to this {@code StringBuffer}. * <p> * Let <i>n</i> be the length of the old character sequence, the one * contained in the {@code StringBuffer} just prior to execution of the * {@code append} method. Then the character at index <i>k</i> in * the new character sequence is equal to the character at index <i>k</i> * in the old character sequence, if <i>k</i> is less than <i>n</i>; * otherwise, it is equal to the character at index <i>k-n</i> in the * argument {@code sb}. * <p> * This method synchronizes on {@code this}, the destination * object, but does not synchronize on the source ({@code sb}). * * @param sb the {@code StringBuffer} to append. * @return a reference to this object. * @since 1.4 */ public synchronized StringBuffer append(StringBuffer sb) { toStringCache = null; super.append(sb); return this; } /** * @since 1.8 */ @Override synchronized StringBuffer append(AbstractStringBuilder asb) { toStringCache = null; super.append(asb); return this; } /** * Appends the specified {@code CharSequence} to this * sequence. * <p> * The characters of the {@code CharSequence} argument are appended, * in order, increasing the length of this sequence by the length of the * argument. * * <p>The result of this method is exactly the same as if it were an * invocation of this.append(s, 0, s.length()); * * <p>This method synchronizes on {@code this}, the destination * object, but does not synchronize on the source ({@code s}). * * <p>If {@code s} is {@code null}, then the four characters * {@code "null"} are appended. * * @param s the {@code CharSequence} to append. * @return a reference to this object. * @since 1.5 */ @Override public synchronized StringBuffer append(CharSequence s) { toStringCache = null; super.append(s); return this; } /** * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.5 */ @Override public synchronized StringBuffer append(CharSequence s, int start, int end) { toStringCache = null; super.append(s, start, end); return this; } @Override public synchronized StringBuffer append(char[] str) { toStringCache = null; super.append(str); return this; } /** * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public synchronized StringBuffer append(char[] str, int offset, int len) { toStringCache = null; super.append(str, offset, len); return this; } @Override public synchronized StringBuffer append(boolean b) { toStringCache = null; super.append(b); return this; } @Override public synchronized StringBuffer append(char c) { toStringCache = null; super.append(c); return this; } @Override public synchronized StringBuffer append(int i) { toStringCache = null; super.append(i); return this; } /** * @since 1.5 */ @Override public synchronized StringBuffer appendCodePoint(int codePoint) { toStringCache = null; super.appendCodePoint(codePoint); return this; } @Override public synchronized StringBuffer append(long lng) { toStringCache = null; super.append(lng); return this; } @Override public synchronized StringBuffer append(float f) { toStringCache = null; super.append(f); return this; } @Override public synchronized StringBuffer append(double d) { toStringCache = null; super.append(d); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} * @since 1.2 */ @Override public synchronized StringBuffer delete(int start, int end) { toStringCache = null; super.delete(start, end); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} * @since 1.2 */ @Override public synchronized StringBuffer deleteCharAt(int index) { toStringCache = null; super.deleteCharAt(index); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} * @since 1.2 */ @Override public synchronized StringBuffer replace(int start, int end, String str) { toStringCache = null; super.replace(start, end, str); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} * @since 1.2 */ @Override public synchronized String substring(int start) { return substring(start, count); } /** * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.4 */ @Override public synchronized CharSequence subSequence(int start, int end) { return super.substring(start, end); } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} * @since 1.2 */ @Override public synchronized String substring(int start, int end) { return super.substring(start, end); } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} * @since 1.2 */ @Override public synchronized StringBuffer insert(int index, char[] str, int offset, int len) { toStringCache = null; super.insert(index, str, offset, len); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public synchronized StringBuffer insert(int offset, Object obj) { toStringCache = null; super.insert(offset, String.valueOf(obj)); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public synchronized StringBuffer insert(int offset, String str) { toStringCache = null; super.insert(offset, str); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public synchronized StringBuffer insert(int offset, char[] str) { toStringCache = null; super.insert(offset, str); return this; } /** * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.5 */ @Override public StringBuffer insert(int dstOffset, CharSequence s) { // Note, synchronization achieved via invocations of other StringBuffer methods // after narrowing of s to specific type // Ditto for toStringCache clearing super.insert(dstOffset, s); return this; } /** * @throws IndexOutOfBoundsException {@inheritDoc} * @since 1.5 */ @Override public synchronized StringBuffer insert(int dstOffset, CharSequence s, int start, int end) { toStringCache = null; super.insert(dstOffset, s, start, end); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuffer insert(int offset, boolean b) { // Note, synchronization achieved via invocation of StringBuffer insert(int, String) // after conversion of b to String by super class method // Ditto for toStringCache clearing super.insert(offset, b); return this; } /** * @throws IndexOutOfBoundsException {@inheritDoc} */ @Override public synchronized StringBuffer insert(int offset, char c) { toStringCache = null; super.insert(offset, c); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuffer insert(int offset, int i) { // Note, synchronization achieved via invocation of StringBuffer insert(int, String) // after conversion of i to String by super class method // Ditto for toStringCache clearing super.insert(offset, i); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuffer insert(int offset, long l) { // Note, synchronization achieved via invocation of StringBuffer insert(int, String) // after conversion of l to String by super class method // Ditto for toStringCache clearing super.insert(offset, l); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuffer insert(int offset, float f) { // Note, synchronization achieved via invocation of StringBuffer insert(int, String) // after conversion of f to String by super class method // Ditto for toStringCache clearing super.insert(offset, f); return this; } /** * @throws StringIndexOutOfBoundsException {@inheritDoc} */ @Override public StringBuffer insert(int offset, double d) { // Note, synchronization achieved via invocation of StringBuffer insert(int, String) // after conversion of d to String by super class method // Ditto for toStringCache clearing super.insert(offset, d); return this; } /** * @since 1.4 */ @Override public int indexOf(String str) { // Note, synchronization achieved via invocations of other StringBuffer methods return super.indexOf(str); } /** * @since 1.4 */ @Override public synchronized int indexOf(String str, int fromIndex) { return super.indexOf(str, fromIndex); } /** * @since 1.4 */ @Override public int lastIndexOf(String str) { // Note, synchronization achieved via invocations of other StringBuffer methods return lastIndexOf(str, count); } /** * @since 1.4 */ @Override public synchronized int lastIndexOf(String str, int fromIndex) { return super.lastIndexOf(str, fromIndex); } /** * @since JDK1.0.2 */ @Override public synchronized StringBuffer reverse() { toStringCache = null; super.reverse(); return this; } @Override public synchronized String toString() { if (toStringCache == null) { toStringCache = Arrays.copyOfRange(value, 0, count); } return new String(toStringCache, true); } /** * Serializable fields for StringBuffer. * * @serialField value char[] * The backing character array of this StringBuffer. * @serialField count int * The number of characters in this StringBuffer. * @serialField shared boolean * A flag indicating whether the backing array is shared. * The value is ignored upon deserialization. */ 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), }; /** * readObject is called to restore the state of the StringBuffer from * a stream. */ 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(); } /** * readObject is called to restore the state of the StringBuffer from * a stream. */ 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); } } |
所謂的 Thread-Safe 事實上就是去避免同一時間點
會有一個以上的執行緒執行同一段任務而發生衝突
換言之,就是同一時間
只允許一個Thread針對物件進行存取處裡
所以StringBuffer會等待 而導致其效能較StringBuilder慢一點
參考連結:
Java 超級新手學習筆記 - == & equals
http://sweeteason.pixnet.net/blog/post/33710656-java-超級新手學習筆記---%3D%3D-%26-equals
【程式】JAVA的Object物件
http://bbkb.pixnet.net/blog/post/10150123-【程式】java的object物件
【工作經驗知識分享】
在工作中跟在學校很大差別在於
當你在交辦事情時
盡量要簡潔並就重點論述
工作場合針對交代事項並不看重推倒過程
只看中結果、結論
盡量於交代事情或詢問時
是給予選擇題(採用哪個方案)而避免申論題
老闆並沒有這麼多美國時間!!!
過程或是相關Study文件
可以作為附件 待上頭有空時做瀏覽
留言
張貼留言