工具類系列---【java8新特性-字符串拼接工具StringJoiner類】


前言:

StringJoiner是Java8新出的一個類,用於構造由分隔符分隔的字符序列,並可選擇性地從提供的前綴開始和以提供的后綴結尾。省的我們開發人員再次通過StringBuffer或者StingBuilder拼接。

用法示例:

StringJoiner sj = new StringJoiner(":", "[", "]");
sj.add("hu").add("jun").add("wei");
String desiredString = sj.toString();

輸出結果:

[hu:jun:wei]

源碼分析:

 

    public String toString() {
        if (value == null) {
            return emptyValue;//沒有值將返回空值或者后續設置的空值
        } else {
            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;
            }
        }
    }
    初始化,先添加前綴,有了之后每次先添加間隔符,StringBuilder后續append字符串
    public StringJoiner add(CharSequence newElement) {
        prepareBuilder().append(newElement);
        return this;
    }
    //合並StringJoiner,注意后面StringJoiner 的前綴就不要了,后面的appen進來
    public StringJoiner merge(StringJoiner other) {
        Objects.requireNonNull(other);
        if (other.value != null) {
            final int length = other.value.length();
            // 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;
    }

    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());
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM