简体   繁体   English

字符串列表始终为null

[英]String List always null

I'm trying to initialize a list of strings as private static final but I always get the value of l as null, and if I declare it as shown in the second snippet of code it works. 我正在尝试将字符串列表初始化为私有static final,但是我总是将l的值设置为null,并且如果我如第二段代码所示进行声明,则可以正常工作。

What I'm trying to do is add the elements of a list I declare to a trie to match some pattern later... 我想做的是将我声明的列表的元素添加到特里以稍后匹配某些模式...

Any thoughts on why the null value in the first example and how can I correct it? 关于为什么第一个示例中的null值有什么想法,我该如何纠正? Thanks 谢谢

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();
    }
}
public class Myclass {
    public static final Myclass INSTANCE = new Myclass();

    private static final List<String> l = Arrays.asList("ofo", "oof", "foo");

Static initialization is done in the order of declaration. 静态初始化按声明的顺序进行。 This means that INSTANCE is initialized before l , so the constructor of Myclass reads the uninitialized value of l . 这意味着INSTANCEl之前初始化,因此Myclass的构造函数读取l的未初始化值。

Reverse the order of the declarations: 颠倒声明的顺序:

public class Myclass {
    private static final List<String> l = Arrays.asList("ofo", "oof", "foo");

    public static final Myclass INSTANCE = new Myclass();

Or, if you don't actually require l otherwise, consider passing it as a constructor parameter. 或者,如果您实际上实际上不需要l ,请考虑将其作为构造函数参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM