我有一个使用单词列表的程序(例如/usr/share/dict/words 中的所有单词)。单词列表永远不会被修改,所以我想我应该将其设置为静态最终的。但我怎样才能最终完成呢?我当前的实现如下所示(我在需要时延迟加载单词列表,尽管我不确定延迟部分是否必要,因为列表并不是那么大或加载速度慢):
private static List<String> WORDS; // adding a final modifier doesn't work here
private static List<String> getWords() throws IOException {
if (WORDS == null) {
List<String> words = new LinkedList<String>();
String line;
BufferedReader br = new BufferedReader(new FileReader("my_dictionary.txt"));
while ((line = br.readLine()) != null) {
words.add(line);
}
WORDS = words;
}
return WORDS;
}
在上面的代码中,我不允许将 WORDS
final
。关于如何做到这一点有什么建议吗? (是否将其定为最终
真的很重要吗?)
编辑:我想一种方法是通过以下方式:
private static final List<String> WORDS = getWords();
private static List<String> getWords() throws IOException {
List<String> words = new LinkedList<String>();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader("my_dictionary.txt"));
while ((line = br.readLine()) != null) {
words.add(line);
}
} catch (IOException e) {
System.out.println("Error reading dictionary: " + e);
}
return words;
}
但这失去了延迟加载部分(尽管这可能并不像final
那么重要?也许我太努力“按照书本”做事了?)。
最佳答案
您可以使用 ImmutableList
来自Guava libraries以防止其被修改。
所以你可以这样做:
private static List<String> WORDS;
private static List<String> getWords() throws IOException {
if (WORDS == null) {
List<String> words = new LinkedList<String>();
String line;
BufferedReader br = new BufferedReader(new FileReader("my_dictionary.txt"));
while ((line = br.readLine()) != null) {
words.add(line);
}
WORDS = ImmutableList.copyOf(words);
}
return WORDS;
}
关于Java:从字典中延迟加载单词:如何使其静态最终?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6171995/