StringJoiner是什麼?
StringJoiner是Java8新出的一個類,用於構造由分隔符分隔的字符序列,並可選擇性地從提供的前綴開始和以提供的後綴結尾。方便開發人員再次通過StringBuffer或者StingBuilder拼接。
應用實例:
StringJoiner sj = new StringJoiner(":", "(", ")");
sj.add("hello").add("world").add("hah");
String sjString = sj.toString();
輸出的代碼爲:
(hello:world:hah)
下面是其源碼加深理解:
package java.util;
public final class StringJoiner {
private final String prefix;//前綴
private final String delimiter;//間隔符
private final String suffix;//後綴
private StringBuilder value;//值
private String emptyValue;//空值
public StringJoiner(CharSequence delimiter) {
this(delimiter, "", "");//默認前綴和後綴爲"",重載調用
}
public StringJoiner(CharSequence delimiter,
CharSequence prefix,
CharSequence suffix) {
//間隔符,前綴和後綴判斷是否爲null,null將拋出異常
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");
// 成員變量賦值
this.prefix = prefix.toString();
this.delimiter = delimiter.toString();
this.suffix = suffix.toString();
this.emptyValue = this.prefix + this.suffix;//空值被設置爲只有前後綴
}
//設置空值,檢查是否爲null
public StringJoiner setEmptyValue(CharSequence emptyValue) {
this.emptyValue = Objects.requireNonNull(emptyValue,
"The empty value must not be null").toString();
return this;
}
@Override
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());
}
}