放棄 StringBuilder!用Java8的StringJoiner
在閱讀項(xiàng)目代碼時(shí),突然看到了StringJoiner這個(gè)類的使用,感覺很有意思。
對(duì)實(shí)際開發(fā)中也有用,原理上是運(yùn)用了StringBuilder的一個(gè)拼接字符串的封裝處理。
為什么會(huì)新增這樣一個(gè)string輔助類?
原有的stringbuilder太死板,不支持分割,如果想讓最終的字符串以逗號(hào)隔開,需要這樣寫
- StringBuilder sb = new StringBuilder();
- IntStream.range(1,10).forEach(i->{
- sb.append(i+"");
- if( i < 10){
- sb.append(",")
- }
- });
是不是太死板了,不好用,StringJoiner怎樣寫呢?
- StringJoiner sj = new StringJoiner(",");
- IntStream.range(1,10).forEach(i->sj.add(i+""));
有哪些平時(shí)用的還比較少的功能:
- setEmptyValue, 默認(rèn)情況下的emptyValue是前綴加后綴, 用戶可自定義emptyValue
- merge(StringJoiner other),合并另外一個(gè)joiner
- length, 當(dāng)前長度,為空看emptyValue的長度
讓我實(shí)現(xiàn)StringJoiner,我會(huì)怎么辦呢?
- 維護(hù)一個(gè)List,最后toString的時(shí)候join一下就好了。優(yōu)勢(shì):實(shí)現(xiàn)非常方便 缺點(diǎn):list太浪費(fèi)空間(擴(kuò)容時(shí)都是按照系數(shù)擴(kuò)容的)
- 在StringBuilder基礎(chǔ)上改造(jdk實(shí)現(xiàn)方式就是以組合的形式增強(qiáng)的StringBuilder
jdk實(shí)現(xiàn)的源碼分析
- 成員變量
- private final String prefix;
- private final String delimiter;
- private final String suffix;
- /*
- * StringBuilder value -- at any time, the characters constructed from the
- * prefix, the added element separated by the delimiter, but without the
- * suffix, so that we can more easily add elements without having to jigger
- * the suffix each time.
- */
- private StringBuilder value;
- /*
- * By default, the string consisting of prefix+suffix, returned by
- * toString(), or properties of value, when no elements have yet been added,
- * i.e. when it is empty. This may be overridden by the user to be some
- * other value including the empty String.
- */
- private String emptyValue;
其實(shí)從成員變量的注釋里就能看出他們的作用和需要注意的點(diǎn)了
- 構(gòu)造函數(shù)
- public StringJoiner(CharSequence delimiter,
- CharSequence prefix,
- CharSequence suffix) {
- Objects.requireNonNull(prefix, "The prefix must not be null");
- Objects.requireNonNull(delimiter, "The delimiter must not be null");
- Objects.requireNonNull(suffix, "The suffix must not be null");
- // make defensive copies of arguments
- this.prefix = prefix.toString();
- this.delimiter = delimiter.toString();
- this.suffix = suffix.toString();
- // ?。?!構(gòu)造時(shí)就直接將emptyValue拼接好了。
- thisthis.emptyValue = this.prefix + this.suffix;
- }
為什么要一開始就構(gòu)造好呢?如果我想直接自定義emptyValue直接用構(gòu)造函數(shù)初始化不是更方便嗎?是因?yàn)榻^大多數(shù)場(chǎng)景下都不會(huì)自定義emptyValue的場(chǎng)景嗎?不對(duì)啊,感覺這個(gè)場(chǎng)景非常必要啊。。。
- 添加元素
- public StringJoiner add(CharSequence newElement) {
- prepareBuilder().append(newElement);
- return this;
- }
- private StringBuilder prepareBuilder() {
- // 從構(gòu)造函數(shù)和類變量的聲明可以看出,沒有添加元素前stringbuilder是沒有初始化的
- if (value != null) {
- // 已經(jīng)有元素存在的情況下,添加元素前先將分隔符添加進(jìn)去
- value.append(delimiter);
- } else {
- // 沒有元素存在的情況下先把前綴加進(jìn)去
- value = new StringBuilder().append(prefix);
- }
- return value;
- }
可以看出再添加元素的過程中就已經(jīng)把前綴和分割字符什么的都處理好了,全部都在stringbuilde中了,唯一沒有處理的就是后綴。 為什么?這樣做tostring什么的時(shí)候真的超級(jí)方便的有木有。。。。。
- 關(guān)鍵的toString
- public String toString() {
- if (value == null) {
- // 這里如果沒有自定義空值就是前綴+后綴咯。。
- return emptyValue;
- } else {
- // 為什么不直接value.toString()+suffix?????
- if (suffix.equals("")) {
- return value.toString();
- } else {
- int initialLength = value.length();
- String result = value.append(suffix).toString();
- // reset value to pre-append initialLength
- value.setLength(initialLength);
- return result;
- }
- }
- }
為什么不直接value.toString()+suffix?答案在merge方法
- merge
- public StringJoiner merge(StringJoiner other) {
- Objects.requireNonNull(other);
- if (other.value != null) {
- final int length = other.value.length();
- // 下面這段注釋是說避免merge(this)時(shí)受影響,為什么?
- // lock the length so that we can seize the data to be appended
- // before initiate copying to avoid interference, especially when
- // merge 'this'
- StringBuilder builder = prepareBuilder();
- builder.append(other.value, other.prefix.length(), length);
- }
- return this;
- }
- private StringBuilder prepareBuilder() {
- if (value != null) {
- value.append(delimiter);
- } else {
- value = new StringBuilder().append(prefix);
- }
- return value;
- }
merge的思路是用當(dāng)前的striingBuilder去append other的value(必須去掉前綴),源碼注釋中的merge 'this'問題是什么呢?prepareBuilder()的時(shí)候可能會(huì)先append(delimiter),如果other就是this,那么length其實(shí)就多了一個(gè)delimiter,此時(shí)append還是得以添加前的length為準(zhǔn)。
merge的實(shí)現(xiàn)方式?jīng)Q定了toString時(shí)不能直接value.append(suffix).toString(),因?yàn)?builder.append(other.value, other.prefix.length(), length);這行代碼,默認(rèn)加上suffix后這里的merge的length得減去suffix的length(嗯,看來作者是想得多好多),而且merge時(shí)得把另外一個(gè)sj的內(nèi)容append到當(dāng)前這個(gè)sj的suffix之前(想想就麻煩多了~)
- length
- public int length() {
- // Remember that we never actually append the suffix unless we return
- // the full (present) value or some sub-string or length of it, so that
- // we can add on more if we need to.
- return (value != null ? value.length() + suffix.length() :
- emptyValue.length());
- }
沒什么好說的,記住length不只是add的元素的length,還有前后綴。
總結(jié)
- 基于StringBuilder實(shí)現(xiàn),add時(shí)就把prefix和分隔符給加上了,suffix永遠(yuǎn)都不加,知道toString和length調(diào)用時(shí)才加入計(jì)算。這樣帶來的merge操作實(shí)現(xiàn)的極大便利性!?。。。W(xué)到了,真的不錯(cuò)
- emptyValue這個(gè)一定要構(gòu)造時(shí)就生成嗎?用戶想有自己的默認(rèn)值還需要先構(gòu)造實(shí)例再注入嗎。。。。這個(gè)覺得還是有點(diǎn)奇怪
- Objects這個(gè)工具方法是返回的校驗(yàn)的值本身,不錯(cuò)。
- public StringJoiner setEmptyValue(CharSequence emptyValue) {
- // 注意這個(gè)Objects.requireNonNull方法是return的第一個(gè)參數(shù)。。。
- this.emptyValue = Objects.requireNonNull(emptyValue,
- "The empty value must not be null").toString();
- return this;
- }