日本a√视频在线,久久青青亚洲国产,亚洲一区欧美二区,免费g片在线观看网站

        <style id="k3y6c"><u id="k3y6c"></u></style>
        <s id="k3y6c"></s>
        <mark id="k3y6c"></mark>
          
          

          <mark id="k3y6c"></mark>

          "); //-->

          博客專欄

          EEPW首頁(yè) > 博客 > 放棄 StringBuilder!Java8的StringJoiner,真香!

          放棄 StringBuilder!Java8的StringJoiner,真香!

          發(fā)布人:編碼之外 時(shí)間:2021-07-25 來(lái)源:工程師 發(fā)布文章
          來(lái)源:jianshu.com/p/469fe8fdd3be


          • 為什么會(huì)新增這樣一個(gè)string輔助類?
          • 讓我實(shí)現(xiàn)StringJoiner,我會(huì)怎么辦呢?
          • jdk實(shí)現(xiàn)的源碼分析
          • 總結(jié)



          在閱讀項(xiàng)目代碼時(shí),突然看到了StringJoiner這個(gè)類的使用,感覺(jué)很有意思。

          對(duì)實(shí)際開(kāi)發(fā)中也有用,原理上是運(yùn)用了StringBuilder的一個(gè)拼接字符串的封裝處理。

          為什么會(huì)新增這樣一個(gè)string輔助類?

          原有的stringbuilder太死板,不支持分割,如果想讓最終的字符串以逗號(hào)隔開(kāi),需要這樣寫

          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)前長(zhǎng)度,為空看emptyValue的長(zhǎng)度
          讓我實(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拼接好了。
                  this.emptyValue = this.prefix + this.suffix;
              }

          為什么要一開(kāi)始就構(gòu)造好呢?如果我想直接自定義emptyValue直接用構(gòu)造函數(shù)初始化不是更方便嗎?是因?yàn)榻^大多數(shù)場(chǎng)景下都不會(huì)自定義emptyValue的場(chǎng)景嗎?不對(duì)啊,感覺(jué)這個(gè)場(chǎng)景非常必要啊。。。

          • 添加元素
          public StringJoiner add(CharSequence newElement) {
                  prepareBuilder().append(newElement);
                  return this;
          }

          private StringBuilder prepareBuilder() {
                  // 從構(gòu)造函數(shù)和類變量的聲明可以看出,沒(méi)有添加元素前stringbuilder是沒(méi)有初始化的
                  if (value != null) {
                      // 已經(jīng)有元素存在的情況下,添加元素前先將分隔符添加進(jìn)去
                      value.append(delimiter);
                  } else {
                      // 沒(méi)有元素存在的情況下先把前綴加進(jìn)去
                      value = new StringBuilder().append(prefix);
                  }
                  return value;
          }

          可以看出再添加元素的過(guò)程中就已經(jīng)把前綴和分割字符什么的都處理好了,全部都在stringbuilde中了,唯一沒(méi)有處理的就是后綴。 為什么?這樣做tostring什么的時(shí)候真的超級(jí)方便的有木有。。。。。

          • 關(guān)鍵的toString
          public String toString() {
              if (value == null) {
                  // 這里如果沒(méi)有自定義空值就是前綴+后綴咯。。
                  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();
                      // 下面這段注釋是說(shuō)避免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'問(wèn)題是什么呢?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(嗯,看來(lái)作者是想得多好多),而且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());
              }

          沒(méi)什么好說(shuō)的,記住length不只是add的元素的length,還有前后綴。

          總結(jié)
          • 基于StringBuilder實(shí)現(xiàn),add時(shí)就把prefix和分隔符給加上了,suffix永遠(yuǎn)都不加,知道toString和length調(diào)用時(shí)才加入計(jì)算。這樣帶來(lái)的merge操作實(shí)現(xiàn)的極大便利性!!?。?!學(xué)到了,真的不錯(cuò)
          • emptyValue這個(gè)一定要構(gòu)造時(shí)就生成嗎?用戶想有自己的默認(rèn)值還需要先構(gòu)造實(shí)例再注入嗎。。。。這個(gè)覺(jué)得還是有點(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;
          }


          *博客內(nèi)容為網(wǎng)友個(gè)人發(fā)布,僅代表博主個(gè)人觀點(diǎn),如有侵權(quán)請(qǐng)聯(lián)系工作人員刪除。



          關(guān)鍵詞: Java8

          技術(shù)專區(qū)

          關(guān)閉