我正在尝试将字符串列表初始化为私有静态最终值,但我总是将值l设为 null,如果我按照第二个代码片段所示声明它,它就可以工作。我正在尝试做的是将我声明的列表的元素添加到 trie 中,以便稍后匹配某些模式......关于为什么第一个示例中的空值以及如何更正它的任何想法?谢谢public class Myclass { public static final Myclass INSTANCE = new Myclass(); private static final List<String> l = Arrays.asList("ofo", "oof", "foo"); private Trie trie; private Myclass() { trie = buildTrie(); } private Trie buildTrie() { TrieBuilder builder = Trie.builder(); Iterator<String> iterator = l.iterator(); while (iterator.hasNext()) { builder.addKeyword(iterator.next()); } return builder.build(); }}public class Myclass { public static final Myclass INSTANCE = new Myclass(); private Trie trie; private Myclass() { List<String> l = Arrays.asList("ofo", "oof", "foo"); trie = buildTrie(); } private Trie buildTrie() { TrieBuilder builder = Trie.builder(); Iterator<String> iterator = l.iterator(); while (iterator.hasNext()) { builder.addKeyword(iterator.next()); } return builder.build(); }}
1 回答
繁星淼淼
TA贡献1775条经验 获得超11个赞
public class Myclass {
public static final Myclass INSTANCE = new Myclass();
private static final List<String> l = Arrays.asList("ofo", "oof", "foo");
静态初始化是按照声明的顺序进行的。这意味着INSTANCE之前已初始化l,因此 的构造函数Myclass读取 的未初始化值l。
颠倒声明的顺序:
public class Myclass {
private static final List<String> l = Arrays.asList("ofo", "oof", "foo");
public static final Myclass INSTANCE = new Myclass();
或者,如果您实际上不需要l其他方式,请考虑将其作为构造函数参数传递。
添加回答
举报
0/150
提交
取消