2011-11-15 45 views
1

我的要求是存儲大塊數據(字符串值),但我很困惑哪一個更好用。我只想追加傳入的數據。StringBuilder VS StringBuffer OR vector Vs ArrayList

e.g. String str1 = "abc" 
    String str2 = "123"; 
    String Str3 = "xyz"; 

suppose i am appending/ adding to (Sbuilder/SBuffer/ vector/ ArrayList) 
one after another, 
     e.g. str1, str2 str3 then output must be "abc123xyz" 
       str2, str1,str3 output must be   "123abcxyz" 

回答

2

使用StringBuilderArrayList

StringBufferVector有線程同步,增加了開銷(除非你需要它,但即便如此,有辦法將它添加到新的類)

+0

謝謝Brian ...! – user1010399

2

從Javadoc中的StringBuffer:

StringBuilder類通常應優先使用這一個,因爲它支持所有相同的操作,但它是快的,因爲它不執行同步。

此外,我認爲矢量是由一個數組內部支持,並且已被大量棄用。如果你想快速附加,那麼你可能想看一下LinkedList(它是稍微比純粹的附加ArrayList更快,因爲你不必定期增長支持數組)。

但是,如果這只是針對字符序列,那麼StringBuilder會針對這種情況進行優化,並且您不應該將Collections與所有開銷混爲一談。

+0

感謝bdares!在我的情況下,字符序列是重要的,並且在運行時大小也是重要的。所以我認爲StringBuilder會很好用。 – user1010399

+0

不知道爲什麼,'vector'在項目中使用的是相同的,但我覺得矢量並不是只對字符串進行整理的正確選擇。 – user1010399

0

如果你不需要要同步你可以避免使用StringBuffer和Vector,而更喜歡StringBuilder和ArrayList。

是否使用StringBuilder或ArrayList取決於您的要求。如果你只想連接字符串SB就足夠了。

0

如果在這種情況下數據大小是可變的,我們使用StringBuffer,因爲StringBuffer類被設計用來創建和操作動態字符串信息。分配給對象的內存是自動的。

0

如果你在一個線程內部完成這個任務,你希望在所有你想實現的都是字符串連接時使用a StringBuilder;對於多種類型,請使用ArrayList

2

Mainlly StringBuffer方法​​而StringBuilder都沒有。

This class [StringBuilder] provides an API compatible with StringBuffer, but with no 
guarantee of synchronization. This class is designed for use as a drop-in replacement 
for 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 StringBuffer as it will be faster under most i implementations. 

* 同*Vector是​​但ArrayList不​​和第二個

A Vector defaults to doubling the size of its array, while the ArrayList increases its 
array size by 50 percent. 

所以要根據您的需要選擇..

+0

StringBuffer幾乎不需要同步,主要是爲了向後兼容。 –