gpt4 book ai didi

java - Guava Joiner 对 null 元素抛出 NPE

转载 作者:行者123 更新时间:2023-12-02 02:53:17 24 4
gpt4 key购买 nike

这里Joiner的初始化是否不正确?我有以下类,当我尝试使用 joiner 连接示例 paths 数组时,我收到一个 NullPointerException

public class CPath {
private static final Joiner joiner = Joiner.on("/");

private String[] elements;

@Override
public String toString() {
return joiner.join(elements);
}
}

// main method
final String[] paths = {"a/b/c", "d", "", null, "e/f/g", "h/i", null, ""};
final CPath c3 = new CPath(paths);
c3.toString(); //<<<< NPE

最佳答案

您必须使用 skipNulls()useForNull(defaultValue),它位于其文档的顶部;

If neither skipNulls() nor useForNull(String) is specified, the joining methods will throw NullPointerException if any given element is null.

所以你必须像这样初始化joiner

Joiner joiner = Joiner.on("/").skipNulls();

Joiner joiner = Joiner.on("/").useForNull("");

Documentation of Joiner from Guava

关于java - Guava Joiner 对 null 元素抛出 NPE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43476156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com