将一个字符串序列用分隔符连接起来。
1.构造函数
只对外提供静态Joiner.on方法来构造joiner
public static Joiner on(String separator) {
return new Joiner(separator);
//调用构造方法,传入分隔符分为字符串和字符两种形式
}
public static Joiner on(char separator) {
//字符转换为字符串
return new Joiner(String.valueOf(separator));
}
private Joiner(String separator) {
this.separator = (String)Preconditions.checkNotNull(separator);
}
2.检查null
忽略空值
public Joiner skipNulls()
@CheckReturnValue
public Joiner useForNull(final String nullText) {
Preconditions.checkNotNull(nullText);
return new Joiner(this) {
CharSequence toString(@Nullable Object part) {
return (CharSequence)(part == null ? nullText : Joiner.this.toString(part));
}
public Joiner useForNull(String nullTextx) {
throw new UnsupportedOperationException("already specified useForNull");
}
public Joiner skipNulls() {
throw new UnsupportedOperationException("already specified useForNull");
}
};
}
public Joiner skipNulls() {
return new Joiner(this) {
//返回新建Joiner 检查列表里是否有null 有null跳过
public A appendTo(A appendable, Iterator parts) throws IOException {
Preconditions.checkNotNull(appendable, "appendable");
Preconditions.checkNotNull(parts, "parts");
Object part;
while(parts.hasNext()) {
part = parts.next();
if (part != null) {
appendable.append(Joiner.this.toString(part));
break;
}
}
while(parts.hasNext()) {
part = parts.next();
//不等于null 添加仅
if (part != null) {
appendable.append(Joiner.this.separator);
appendable.append(Joiner.this.toString(part));
}
}
return appendable;
}
public Joiner useForNull(String nullText) {
throw new UnsupportedOperationException("already specified skipNulls");
}
public Joiner.MapJoiner withKeyValueSeparator(String kvs) {
throw new UnsupportedOperationException("can't use .skipNulls() with maps");
}
};
}
Joiner joiner = Joiner.on("; ").skipNulls();
return joiner.join("Harry", null, "Ron", "Hermione");
3.join
public final String join(@Nullable Object first, @Nullable Object second, Object... rest) {
return this.join(iterable(first, second, rest));
//将元素变成迭代器放入
}
public final String join(Iterable> parts) {
return this.join(parts.iterator());
}
public final String join(Iterator> parts) {
return this.appendTo(new StringBuilder(), parts).toString();
//调用 appendTo串联起来,拼接字符串
}
public final String join(Object[] parts) {
return this.join((Iterable)Arrays.asList(parts));
}
public final StringBuilder appendTo(StringBuilder builder, Iterator> parts) {
try {
this.appendTo((Appendable)builder, (Iterator)parts);
return builder;
} catch (IOException var4) {
throw new AssertionError(var4);
}
}
public final StringBuilder appendTo(StringBuilder builder, Object[] parts) {
return this.appendTo((StringBuilder)builder, (Iterable)Arrays.asList(parts));
}
public final StringBuilder appendTo(StringBuilder builder, @Nullable Object first, @Nullable Object second, Object... rest) {
return this.appendTo(builder, iterable(first, second, rest));
}